8. Dictionaries and Data Structures
Level: BeginnerDuration: 30m
What Is a Dictionary in Python?
A dictionary in Python is used to store data in **key-value pairs**. Unlike lists that use numeric indexes, dictionaries use meaningful keys to access values.
python
user = {
"name": "John",
"age": 25,
"country": "Nigeria"
}
print(user)Dictionaries are perfect when you want to label your data for clarity and easy access.
Accessing and Updating Dictionary Values
python
# Access values by key
print(user["name"]) # John
# Add a new key-value pair
user["email"] = "john@example.com"
# Update a value
user["age"] = 26
# Remove a key
user.pop("country")
Useful Dictionary Methods
python
print(user.keys()) # dict_keys(['name', 'age', 'email'])
print(user.values()) # dict_values(['John', 26, 'john@example.com'])
print(user.items()) # dict_items([('name', 'John'), ('age', 26), ('email', 'john@example.com')])Nested Dictionaries
Dictionaries can contain other dictionaries—this is called nesting. This allows us to structure complex data easily.
python
students = {
"student1": {"name": "Aisha", "age": 20},
"student2": {"name": "Kelvin", "age": 22}
}
print(students["student1"]["name"]) # AishaDictionaries vs Other Data Structures
| Type | Example | Best Use |
|---|---|---|
| List | [10, 20, 30] | Ordered collection |
| Tuple | ("red", "blue") | Fixed data |
| Set | {1, 2, 3} | Unique items |
| Dictionary | {"name": "Tom"} | Structured data with labels |
Real World Example
Imagine you're building a user profile feature for a website. A dictionary is a perfect way to store user information.
python
profile = {
"username": "techgirl",
"followers": 1200,
"is_verified": True,
"skills": ["Python", "Django", "React"]
}
print(profile)Mini Exercise
Create a dictionary called `car` with keys: `brand`, `model`, `year`. Update the `year`, add a `color`, and print the final dictionary.
python
# Your code here
car = {}
print(car)