Sub topic 2
Iterating with `keys()`, `values()` and `items()`
Assume you know variables, for loops, f-strings, and mutable versus immutable objects. A dictionary stores key-value pairs. Its iteration methods return dynamic views into those pairs.
Dictionary views
keys()iterates over keys.values()iterates over values.items()iterates over(key, value)tuples.
Use items() when you need both parts of an entry:
scores = {"ana": 90, "ben": 72, "cy": 85}
for name in scores:
print(name) # Iterates over keys
for score in scores.values():
print(score)
for name, score in scores.items():
print(f"{name}: {score}")A view reflects later changes to the dictionary. It is not an independent list:
scores = {"ana": 90}
keys = scores.keys()
scores["ben"] = 72
print(list(keys)) # ['ana', 'ben']The in operator checks keys by default. Use scores.values() if you need to search values.
Insertion order and equality
Python dictionaries preserve insertion order. Updating an existing key keeps its position. Removing and adding that key again places it at the end.
Dictionary equality compares key-value contents, not insertion order:
first = {"a": 1, "b": 2}
second = {"b": 2, "a": 1}
print(first == second) # TrueThe two dictionaries contain the same mappings even though their iteration order differs.
Merging dictionaries
Python 3.9 introduced | for creating a merged dictionary and |= for updating one in place. If both dictionaries contain a key, the right-hand value wins.
defaults = {"theme": "light", "font": 12}
overrides = {"font": 14, "size": "medium"}
merged = defaults | overrides
print(merged) # {'theme': 'light', 'font': 14, 'size': 'medium'}
defaults |= overrides
print(defaults) # {'theme': 'light', 'font': 14, 'size': 'medium'}For compatibility with older Python versions, dictionary unpacking also creates a merged dictionary:
merged = {**defaults, **overrides}Exercise
Which value does {"mode": "safe"} | {"mode": "fast"} store for "mode"?
Show answer
"fast", because values from the right-hand dictionary override duplicate keys.