Dictionary Methods
.keys(), .values(), .items(), looping over dicts, counting patterns, and nested dicts.
Yesterday I built a customer profile with individual keys. But what if I have 500 customers, each with their own dictionary? How do I work with all of them at once?
That's where dictionary iteration methods come in. Every dictionary gives you three ways to look at its contents:
customer = {"name": "Alice", "email": "alice@example.com", "total": 2450}
customer.keys() # dict_keys(["name", "email", "total"])
customer.values() # dict_values(["Alice", "alice@example.com", 2450])
customer.items() # dict_items([("name", "Alice"), ("email", "alice@example.com"), ("total", 2450)])
.keys() gives you all the keys, .values() gives you all the values, and .items() gives you key-value pairs as tuples. You'll use these constantly in loops.
Wait, I can loop through a dictionary? That changes everything. Show me.
Several ways, depending on what you need:
revenue = {"Jan": 4200, "Feb": 3800, "Mar": 5100}
# Loop over keys (default behavior)
for month in revenue:
print(month) # Jan, Feb, Mar
# Loop over values
for amount in revenue.values():
print(amount) # 4200, 3800, 5100
# Loop over both — the most common pattern
for month, amount in revenue.items():
print(f"{month}: ${amount:,}")
The .items() loop is the workhorse. You unpack each tuple into two variables — the key and the value — and work with both. Think of it like walking through a two-column spreadsheet: column A is the key, column B is the value, and you're reading each row.
I'm starting to see this. So if I had a spreadsheet with months in column A and revenue in column B, a dictionary is basically that whole table?
Exactly. And now here's one of the most useful patterns in Python. Say your boss sends you a list of sales regions and wants to know how many transactions came from each one:
regions = ["East", "West", "East", "North", "West", "East"]
counts = {}
for region in regions:
counts[region] = counts.get(region, 0) + 1
print(counts) # {"East": 3, "West": 2, "North": 1}
The .get(region, 0) + 1 pattern is elegant: "get the current count (or 0 if this is the first time we've seen this region), then add 1." One line per iteration, and it handles any number of unique values.
You could do this in a spreadsheet with COUNTIF — but this approach works on 10 items or 10 million, and you never have to set up a separate table.
Can a dictionary contain another dictionary? Like, a customer record where one of the fields is their address, which itself has street, city, state?
Absolutely. Nested dictionaries let you model structured data:
customers = {
"Alice": {"email": "alice@example.com", "total": 2450},
"Bob": {"email": "bob@example.com", "total": 1800},
"Charlie": {"email": "charlie@example.com", "total": 3200}
}
# Access nested values with chained brackets
customers["Alice"]["total"] # 2450
customers["Bob"]["email"] # "bob@example.com"
You can loop over nested dicts too:
for name, data in customers.items():
print(f"{name}: ${data['total']:,}")
This pattern — a dictionary of dictionaries — is how most real-world data is structured. Think of it as a mini-database: each key is a row identifier, each value is the record.
Can I merge two dictionaries? Like, if I get an update file with new customer data?
Yes. The update() method merges another dictionary into the current one. If keys overlap, the new values win:
defaults = {"color": "blue", "size": "medium", "shape": "circle"}
overrides = {"color": "red", "weight": 10}
defaults.update(overrides)
print(defaults)
# {"color": "red", "size": "medium", "shape": "circle", "weight": 10}
Or use the | operator (Python 3.9+) to create a new merged dict without modifying either original:
merged = defaults | overrides
This is useful when you have defaults and want to apply user-specific overrides — a pattern you'll see in configuration files, API responses, and data pipelines.
When should I use a list vs a dictionary? I'm starting to see them as different tools for different jobs.
Use a list when you have an ordered sequence of similar items — a column of scores, a list of customer names, a batch of tasks. Use a dictionary when you need to look up values by a meaningful key — customer records by name, configuration settings by key, word counts. If you find yourself searching a list by value repeatedly, a dictionary is probably a better fit.
Let's put all of this together.
Practice your skills
Sign up to write and run code in this lesson.
Dictionary Methods
.keys(), .values(), .items(), looping over dicts, counting patterns, and nested dicts.
Yesterday I built a customer profile with individual keys. But what if I have 500 customers, each with their own dictionary? How do I work with all of them at once?
That's where dictionary iteration methods come in. Every dictionary gives you three ways to look at its contents:
customer = {"name": "Alice", "email": "alice@example.com", "total": 2450}
customer.keys() # dict_keys(["name", "email", "total"])
customer.values() # dict_values(["Alice", "alice@example.com", 2450])
customer.items() # dict_items([("name", "Alice"), ("email", "alice@example.com"), ("total", 2450)])
.keys() gives you all the keys, .values() gives you all the values, and .items() gives you key-value pairs as tuples. You'll use these constantly in loops.
Wait, I can loop through a dictionary? That changes everything. Show me.
Several ways, depending on what you need:
revenue = {"Jan": 4200, "Feb": 3800, "Mar": 5100}
# Loop over keys (default behavior)
for month in revenue:
print(month) # Jan, Feb, Mar
# Loop over values
for amount in revenue.values():
print(amount) # 4200, 3800, 5100
# Loop over both — the most common pattern
for month, amount in revenue.items():
print(f"{month}: ${amount:,}")
The .items() loop is the workhorse. You unpack each tuple into two variables — the key and the value — and work with both. Think of it like walking through a two-column spreadsheet: column A is the key, column B is the value, and you're reading each row.
I'm starting to see this. So if I had a spreadsheet with months in column A and revenue in column B, a dictionary is basically that whole table?
Exactly. And now here's one of the most useful patterns in Python. Say your boss sends you a list of sales regions and wants to know how many transactions came from each one:
regions = ["East", "West", "East", "North", "West", "East"]
counts = {}
for region in regions:
counts[region] = counts.get(region, 0) + 1
print(counts) # {"East": 3, "West": 2, "North": 1}
The .get(region, 0) + 1 pattern is elegant: "get the current count (or 0 if this is the first time we've seen this region), then add 1." One line per iteration, and it handles any number of unique values.
You could do this in a spreadsheet with COUNTIF — but this approach works on 10 items or 10 million, and you never have to set up a separate table.
Can a dictionary contain another dictionary? Like, a customer record where one of the fields is their address, which itself has street, city, state?
Absolutely. Nested dictionaries let you model structured data:
customers = {
"Alice": {"email": "alice@example.com", "total": 2450},
"Bob": {"email": "bob@example.com", "total": 1800},
"Charlie": {"email": "charlie@example.com", "total": 3200}
}
# Access nested values with chained brackets
customers["Alice"]["total"] # 2450
customers["Bob"]["email"] # "bob@example.com"
You can loop over nested dicts too:
for name, data in customers.items():
print(f"{name}: ${data['total']:,}")
This pattern — a dictionary of dictionaries — is how most real-world data is structured. Think of it as a mini-database: each key is a row identifier, each value is the record.
Can I merge two dictionaries? Like, if I get an update file with new customer data?
Yes. The update() method merges another dictionary into the current one. If keys overlap, the new values win:
defaults = {"color": "blue", "size": "medium", "shape": "circle"}
overrides = {"color": "red", "weight": 10}
defaults.update(overrides)
print(defaults)
# {"color": "red", "size": "medium", "shape": "circle", "weight": 10}
Or use the | operator (Python 3.9+) to create a new merged dict without modifying either original:
merged = defaults | overrides
This is useful when you have defaults and want to apply user-specific overrides — a pattern you'll see in configuration files, API responses, and data pipelines.
When should I use a list vs a dictionary? I'm starting to see them as different tools for different jobs.
Use a list when you have an ordered sequence of similar items — a column of scores, a list of customer names, a batch of tasks. Use a dictionary when you need to look up values by a meaningful key — customer records by name, configuration settings by key, word counts. If you find yourself searching a list by value repeatedly, a dictionary is probably a better fit.
Let's put all of this together.
Practice your skills
Sign up to write and run code in this lesson.