Day 10: Dictionaries in Python – Mastering Key-Value Data
Dictionaries are one of the most powerful and widely used data structures in Python. They allow you to store and manage data in a key-value format, which makes them extremely efficient for searching, mapping, and organizing structured information.
If lists are about ordered collections, dictionaries are about meaningful relationships between data.
What is a Dictionary?
A dictionary is an unordered, mutable collection of key-value pairs.
student = {
"name": "Piyush",
"age": 20,
"course": "Python"
}
Key Points:
- Keys must be unique and immutable (string, number, tuple)
- Values can be of any data type
- Dictionaries are defined using {}
Why Dictionaries are Important?
- Fast lookup time: O(1) average complexity
- Used in JSON data (APIs)
- Core structure in backend and data science workflows
- Ideal for representing real-world entities
Creating Dictionaries
# Empty dictionary
data = {}
# Using dict()
data = dict(name="Piyush", age=20)
# Nested dictionary
student = {
"name": "Piyush",
"marks": {
"math": 90,
"science": 85
}
}
Accessing Values
student = {"name": "Piyush", "age": 20}
print(student["name"]) # Direct access
print(student.get("age")) # Safe access
Difference:
- [] → Raises error if key not found
- .get() → Returns None (or default value)
Accessing Nested Dictionary
student = {
"name": "Piyush",
"marks": {
"math": 90,
"science": 85
}
}
print(student["marks"]["math"]) # 90
Safe Way:
print(student.get("marks", {}).get("math"))
Adding and Updating Values
student = {"name": "Piyush"}
# Add new key
student["age"] = 20
# Update existing key
student["name"] = "Rahul"
Removing Elements
student = {"name": "Piyush", "age": 20}
student.pop("age")
del student["name"]
student.clear()
Dictionary Methods
student = {"name": "Piyush", "age": 20}
student.keys()
student.values()
student.items()
Looping Through Dictionary
student = {"name": "Piyush", "age": 20}
for key in student:
print(key, student[key])
for key, value in student.items():
print(key, value)
Real-World Example: Frequency Counter
nums = [1, 2, 2, 3, 3, 3]
freq = {}
for num in nums:
freq[num] = freq.get(num, 0) + 1
print(freq)
Practice Questions
Basic
- Create a dictionary with 3 key-value pairs and print it
- Access a value using a key
- Add a new key-value pair
- Update an existing value
Intermediate
- Check if a key exists in a dictionary
- Print all keys and values separately
- Merge two dictionaries
- Count frequency of elements in a list using dictionary
Advanced
- Create a nested dictionary for 3 students with marks
- Sort a dictionary by keys and values
- Invert a dictionary (swap keys and values)
- Group elements based on frequency
.png)

0 Comments:
Post a Comment