Python Dict Methods: get, keys, values, items
Safely read dict fields with .get() and defaults. Master .keys(), .values(), .items() for iteration over dictionary data.
I wrote amount = sale['amount'] and Python threw a KeyError. The dictionary didn't have that key. I want to avoid that.
That's the exact problem we're solving today. Yesterday you created dictionaries where you controlled every key. Today you're reading from dictionaries where keys might be missing. Real data is messy. A CSV might have extra fields one row and skip them the next. An API response might include optional fields only sometimes. You need a safe way to read from a dictionary when you're not sure the key exists.
The method is called .get().
So instead of sale['amount'], I write sale.get('amount')?
Yes, but there's more. .get() takes two arguments: the key you're looking for, and a default value if the key isn't there. Watch:
# Risky: throws KeyError if 'notes' doesn't exist
sale = {'name': 'Alice Chen', 'amount': 1250.00, 'region': 'West'}
print(sale['notes']) # KeyError!
# Safe: returns the default if 'notes' is missing
print(sale.get('notes', 'No notes')) # No notes
print(sale.get('amount', 0.0)) # 1250.0
The first call returns 'No notes' because 'notes' isn't in the dictionary—and that's fine, we provided a fallback. The second call returns 1250.0 because 'amount' is in the dictionary. If the key exists, .get() returns its value. If it doesn't exist, it returns the default.
So I can use .get() to safely read every field in a sale and give each one a sensible default?
Exactly. That's your problem today. You're going to write a function called summarise_record that takes a sale dictionary and returns a formatted summary string. You'll use .get() to safely read name, amount, and region—with defaults for missing fields.
def summarise_record(sale):
name = sale.get('name', 'Unknown')
amount = sale.get('amount', 0.0)
region = sale.get('region', 'Unknown')
return f"{name} ({region}): ${amount:.2f}"
complete = {'name': 'Alice Chen', 'amount': 1250.00, 'region': 'West'}
print(summarise_record(complete)) # Alice Chen (West): $1250.00
incomplete = {'name': 'Bob Kumar'}
print(summarise_record(incomplete)) # Bob Kumar (Unknown): $0.00
empty = {}
print(summarise_record(empty)) # Unknown (Unknown): $0.00
The first call works because all fields are there. The second call uses defaults for missing 'amount' and 'region'. The third call uses defaults for everything. No KeyError anywhere.
OK, so .get() is for reading one field safely. But what if I want to loop through all the keys or all the values?
That's where .keys(), .values(), and .items() come in. Think of them as three views of the same dictionary:
sale = {'name': 'Alice Chen', 'amount': 1250.00, 'region': 'West'}
# .keys() — just the labels
for key in sale.keys():
print(key)
# Prints: name, amount, region
# .values() — just the data
for value in sale.values():
print(value)
# Prints: Alice Chen, 1250.0, West
# .items() — both together
for key, value in sale.items():
print(f"{key}: {value}")
# Prints: name: Alice Chen, amount: 1250.0, region: West
.keys() gives you a list-like object of all the keys. .values() gives you the values. .items() gives you tuples of (key, value) pairs. If you want to print every field for debugging, loop with .items(). If you only care about specific keys, use .get() with a default.
So .items() is like what I'd use if I had a 'notes' field and I wanted to print a summary of everything in the dictionary?
Exactly. You could do:
def debug_sale(sale):
for key, value in sale.items():
print(f" {key}: {value}")
sale = {'name': 'Alice Chen', 'amount': 1250.00, 'region': 'West', 'notes': 'VIP customer'}
debug_sale(sale)
# Prints:
# name: Alice Chen
# amount: 1250.0
# region: West
# notes: VIP customer
Loop through .items() and you get both the key and the value, so you can print or process them together.
So today I'm writing summarise_record that uses .get() for safe reads. And the stretch goal mentions using .items() for debugging. Next lesson is... list comprehensions?
You've been reading ahead! Yes, next lesson you're going to take a list of dictionaries—imagine a CSV with a hundred sales—and process all of them with a one-liner. You'll combine what you learned this week (lists and dictionaries) with a new Python power that makes simple transformations beautiful. But that's tomorrow. Today, master .get() and .items(). You're almost through Week 3.
Practice your skills
Sign up to write and run code in this lesson.
Python Dict Methods: get, keys, values, items
Safely read dict fields with .get() and defaults. Master .keys(), .values(), .items() for iteration over dictionary data.
I wrote amount = sale['amount'] and Python threw a KeyError. The dictionary didn't have that key. I want to avoid that.
That's the exact problem we're solving today. Yesterday you created dictionaries where you controlled every key. Today you're reading from dictionaries where keys might be missing. Real data is messy. A CSV might have extra fields one row and skip them the next. An API response might include optional fields only sometimes. You need a safe way to read from a dictionary when you're not sure the key exists.
The method is called .get().
So instead of sale['amount'], I write sale.get('amount')?
Yes, but there's more. .get() takes two arguments: the key you're looking for, and a default value if the key isn't there. Watch:
# Risky: throws KeyError if 'notes' doesn't exist
sale = {'name': 'Alice Chen', 'amount': 1250.00, 'region': 'West'}
print(sale['notes']) # KeyError!
# Safe: returns the default if 'notes' is missing
print(sale.get('notes', 'No notes')) # No notes
print(sale.get('amount', 0.0)) # 1250.0
The first call returns 'No notes' because 'notes' isn't in the dictionary—and that's fine, we provided a fallback. The second call returns 1250.0 because 'amount' is in the dictionary. If the key exists, .get() returns its value. If it doesn't exist, it returns the default.
So I can use .get() to safely read every field in a sale and give each one a sensible default?
Exactly. That's your problem today. You're going to write a function called summarise_record that takes a sale dictionary and returns a formatted summary string. You'll use .get() to safely read name, amount, and region—with defaults for missing fields.
def summarise_record(sale):
name = sale.get('name', 'Unknown')
amount = sale.get('amount', 0.0)
region = sale.get('region', 'Unknown')
return f"{name} ({region}): ${amount:.2f}"
complete = {'name': 'Alice Chen', 'amount': 1250.00, 'region': 'West'}
print(summarise_record(complete)) # Alice Chen (West): $1250.00
incomplete = {'name': 'Bob Kumar'}
print(summarise_record(incomplete)) # Bob Kumar (Unknown): $0.00
empty = {}
print(summarise_record(empty)) # Unknown (Unknown): $0.00
The first call works because all fields are there. The second call uses defaults for missing 'amount' and 'region'. The third call uses defaults for everything. No KeyError anywhere.
OK, so .get() is for reading one field safely. But what if I want to loop through all the keys or all the values?
That's where .keys(), .values(), and .items() come in. Think of them as three views of the same dictionary:
sale = {'name': 'Alice Chen', 'amount': 1250.00, 'region': 'West'}
# .keys() — just the labels
for key in sale.keys():
print(key)
# Prints: name, amount, region
# .values() — just the data
for value in sale.values():
print(value)
# Prints: Alice Chen, 1250.0, West
# .items() — both together
for key, value in sale.items():
print(f"{key}: {value}")
# Prints: name: Alice Chen, amount: 1250.0, region: West
.keys() gives you a list-like object of all the keys. .values() gives you the values. .items() gives you tuples of (key, value) pairs. If you want to print every field for debugging, loop with .items(). If you only care about specific keys, use .get() with a default.
So .items() is like what I'd use if I had a 'notes' field and I wanted to print a summary of everything in the dictionary?
Exactly. You could do:
def debug_sale(sale):
for key, value in sale.items():
print(f" {key}: {value}")
sale = {'name': 'Alice Chen', 'amount': 1250.00, 'region': 'West', 'notes': 'VIP customer'}
debug_sale(sale)
# Prints:
# name: Alice Chen
# amount: 1250.0
# region: West
# notes: VIP customer
Loop through .items() and you get both the key and the value, so you can print or process them together.
So today I'm writing summarise_record that uses .get() for safe reads. And the stretch goal mentions using .items() for debugging. Next lesson is... list comprehensions?
You've been reading ahead! Yes, next lesson you're going to take a list of dictionaries—imagine a CSV with a hundred sales—and process all of them with a one-liner. You'll combine what you learned this week (lists and dictionaries) with a new Python power that makes simple transformations beautiful. But that's tomorrow. Today, master .get() and .items(). You're almost through Week 3.