What you'll learn
The dictionary is arguably the most important data structure in Python. It stores key → value pairs with lightning-fast lookup — like a real dictionary where you look up a word (the key) to find its definition (the value). You'll use it everywhere.
By the end you'll be able to:
- Create dictionaries and look up values safely
- Add, update, and delete key-value pairs
- Iterate keys, values, and items
- Build dictionaries concisely with dict comprehensions
- Use
Counteranddefaultdictfromcollections
Creating & accessing
A dictionary uses curly braces with key: value pairs. Keys must be unique and immutable (strings, numbers, tuples). You look up a value by its key:
A dictionary maps unique keys to values. Looking up a key is near-instant, no matter how large the dictionary grows.
ages = {"Sara": 25, "Omar": 30}
print(ages["Sara"]) # 25
print(ages.get("Aisha", 0)) # 0 (a default if the key is missing)
print("Omar" in ages) # True
print(len(ages)) # 2Use .get() for safety
ages["missing"] raises a KeyError. .get(key, default) returns your default instead of crashing — much safer when a key might not exist.Modifying dictionaries
Dictionaries are mutable. Assigning to a key adds it (or updates it if it exists); del removes it; and .update() merges another dictionary in:
ages = {"Sara": 25}
ages["Omar"] = 30 # add a new key
ages["Sara"] = 26 # update an existing key
ages.update({"Aisha": 22, "Sam": 40})
del ages["Omar"] # delete a key
print(ages)Note
| operator: combined = a | b.Iterating over dictionaries
Looping over a dictionary gives you its keys by default. To get keys and values together, use .items() — one of the most common patterns in all of Python:
prices = {"apple": 1.5, "banana": 0.5}
for key in prices: # iterating gives the KEYS
print(key)
for fruit, price in prices.items(): # .items() gives key AND value
print(f"{fruit}: {price}")| Method | Returns |
|---|---|
.keys() | all the keys |
.values() | all the values |
.items() | (key, value) pairs |
.get(k, default) | value for k, or default |
.setdefault(k, d) | get k, inserting d if missing |
.pop(k) | remove k and return its value |
Dict comprehensions
Just like list comprehensions (coming in Module 12), you can build a dictionary in one readable line with a dict comprehension: {key: value for item in iterable}:
squares = {n: n * n for n in range(1, 6)}
print(squares)
# invert a dictionary (swap keys and values)
prices = {"apple": 1.5, "banana": 0.5}
by_price = {price: fruit for fruit, price in prices.items()}
print(by_price)Counter & defaultdict
The collections module offers specialised dictionaries that save you writing common code by hand. Counter tallies how often things appear — perfect for counting words, votes, or events:
from collections import Counter
votes = ["yes", "no", "yes", "yes", "no"]
counts = Counter(votes)
print(counts) # Counter({'yes': 3, 'no': 2})
print(counts["yes"]) # 3
print(counts.most_common(1)) # [('yes', 3)]Note
defaultdict is another gem: it auto-creates a default value for missing keys (like an empty list), so you can write groups[key].append(x) without first checking whether key exists. Both are covered more in Module 29.Recap & quick check
Key takeaways
- Dictionaries map unique, immutable keys to values with near-instant lookup.
- Use .get(key, default) to avoid a KeyError when a key might be missing.
- Assigning to a key adds or updates it; del removes; .update() merges. Insertion order is preserved.
- Iterate with .items() to get keys and values together.
- Build them with dict comprehensions; Counter tallies frequencies and defaultdict handles missing keys.
Quick check
1. What does a dictionary store?
2. How do you safely get a value that might be missing?
3. Which method gives you keys and values together while iterating?
4. What must dictionary keys be?
5. What does collections.Counter do?
Excellent — you've mastered Python's most-used structure. Next up: Module 11 — Sets.