Module 2 Lesson 4: Dictionaries
Learn to store data using meaningful labels. Master Python dictionaries, key-value pairs, and nested data structures.
Module 2 Lesson 4: Dictionaries
Lists and Tuples are great, but they have a limitation: search by position. If you have a list of 1,000 users, finding "Alex's email" requires knowing exactly where Alex is in that list. Dictionaries solve this problem by allowing you to store data as Key-Value Pairs.
Lesson Overview
In this lesson, we will cover:
- Creating Dictionaries: Using curly braces
{}. - Keys and Values: The "Label" and the "Data."
- Accessing Data: Looking up values by their keys.
- Modifying Dictionaries: Adding, updating, and removing entries.
- Nested Dictionaries: Data inside of data.
1. Creating a Dictionary
A dictionary uses curly braces {}. Each entry is a key: value pair.
user = {
"name": "Alex",
"age": 25,
"is_pro": True
}
- Key: Must be unique and immutable (usually a string).
- Value: Can be anything (string, number, list, or even another dictionary!).
2. Accessing and Updating Data
You "look up" a value by using its key in square brackets.
# Access
print(user["name"]) # Output: Alex
# Update
user["age"] = 26
# Add a New Key
user["hobby"] = "Photography"
Pro Tip: If you try to access a key that doesn't exist, Python will crash. To avoid this, use the .get() method!
email = user.get("email", "Not Found")
3. Dictionary Methods
| Method | Description | Example |
|---|---|---|
.keys() | Get all the labels | user.keys() |
.values() | Get all the data | user.values() |
.items() | Get pairs as tuples | user.items() |
.pop(key) | Remove item by key | user.pop("age") |
.clear() | Empty the dictionary | user.clear() |
4. Loops and Dictionaries
You can loop through a dictionary to see all its contents.
capitals = {"France": "Paris", "Spain": "Madrid", "Italy": "Rome"}
for country, city in capitals.items():
print(f"The capital of {country} is {city}.")
5. Nested Dictionaries
Dictionaries can hold other dictionaries. This is how complex data (like what you get from social media APIs) is structured.
employees = {
"emp1": {"name": "Sara", "job": "Developer"},
"emp2": {"name": "Bill", "job": "Manager"}
}
print(employees["emp1"]["name"]) # Output: Sara
Practice Exercise: The Contact Book
Create a file named contacts.py.
- Create a dictionary named
contactwith keys forname,phone, andemail. - Add a new key-value pair for
address. - Update the
phonenumber to a new string. - Print out only the keys of the dictionary.
- Use a
forloop to print each piece of information in the format:"Label: Value".
Quick Knowledge Check
- What symbols do we use to create a Dictionary?
- Can a Dictionary have two identical keys?
- How do you safely access a key that might not exist?
- What is the difference between a key and a value?
Key Takeaways
- Dictionaries store data in
key: valuepairs. - They are optimized for fast lookups using keys.
- Keys must be unique and immutable.
- Nesting allows you to model complex, real-world information.
What’s Next?
We’ve covered the most structured ways to store data. But what if you just need a "bag" of unique items? In Lesson 5, we’ll look at Sets and learn how to handle unique collections!