Python - Dictionaries
Overview
Estimated time: 25–35 minutes
Use dictionaries (hash maps) for key-value storage. Learn lookups, updates, iteration, and helpful methods.
Learning Objectives
- Create and update dicts; understand key immutability and hashing.
- Use
get
,setdefault
,update
, and dict comprehensions. - Iterate with
keys()
,values()
, anditems()
.
Prerequisites
Basics
user = {"name": "Ada", "age": 36}
user["role"] = "admin"
print(user.get("email", "(none)"))
Counting with dict
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts)
Comprehensions and iteration
squares = {n: n*n for n in range(5)}
for k, v in squares.items():
print(k, v)
Common Pitfalls
- Using mutable types as keys; keys must be hashable (e.g., tuples, not lists).
- Assuming
dict
reorder; since 3.7, insertion order is preserved by language guarantee.
Checks for Understanding
- How do you get a default value for a missing key?
- Which method returns key-value pairs for iteration?
Show answers
dict.get(key, default)
dict.items()
Exercises
- Build a frequency map of words from a string.
- Invert a dict where values are unique (value → key).