Lesson 9: Dictionaries in Depth

1. Introduction to Dictionaries
Dictionaries are one of the most powerful and flexible data structures in Python.
They store data as key-value pairs and are extremely useful when we need to access data quickly using a unique key.
Example:
student = {
"name": "Alice",
"age": 22,
"major": "Computer Science"
}
print(student["name"]) # Output: Alice
2. Dictionary Properties
- Unordered (before Python 3.7), but insertion-ordered in Python 3.7+.
- Mutable: values can be changed.
- Unique keys: no duplicates allowed.
3. Creating Dictionaries
# Using curly braces
person = {"name": "John", "age": 30}
# Using dict() function
person2 = dict(name="Emma", age=25)
4. Accessing Dictionary Values
car = {"brand": "Tesla", "model": "Model S"}
print(car["brand"]) # Tesla
print(car.get("model")) # Model S
5. Modifying Dictionaries
car["color"] = "red" # Adding a new key-value pair
car["model"] = "Model X" # Updating existing value
6. Dictionary Methods
Method | Description | Example |
---|---|---|
keys() | Returns all keys | car.keys() → ['brand','model','color'] |
values() | Returns all values | car.values() → ['Tesla','Model X','red'] |
items() | Returns key-value pairs | car.items() |
update() | Updates dictionary | car.update({"year": 2023}) |
pop() | Removes key | car.pop("color") |
clear() | Removes all items | car.clear() |
7. Looping Through Dictionaries
for key, value in car.items():
print(key, ":", value)
# Output:
# brand : Tesla
# model : Model X
# year : 2023
8. Nested Dictionaries
Dictionaries can hold other dictionaries inside them.
students = {
"student1": {"name": "Alice", "age": 20},
"student2": {"name": "Bob", "age": 22}
}
print(students["student1"]["name"]) # Output: Alice
9. Dictionary Comprehension
squares = {x: x*x for x in range(5)}
print(squares) # {0:0, 1:1, 2:4, 3:9, 4:16}
10. Summary
- Dictionaries store key-value pairs.
- Keys are unique and immutable (e.g., strings, numbers, tuples).
- Methods like
.keys()
,.values()
,.items()
, and.update()
make dictionaries powerful. - Useful for storing structured data like JSON.