Lesson 6 of 10
Dictionaries have three methods for getting at their contents, and each one pairs naturally with
a for loop.
.keys(), .values(), .items()
scores = {"ada": 90, "grace": 95, "alan": 88}
print(list(scores.keys()))
print(list(scores.values()))
print(list(scores.items()))
.items() gives you (key, value) tuples — which is exactly what you unpack in a loop.
Looping
Looping over a dictionary directly gives you its keys:
scores = {"ada": 90, "grace": 95}
for name in scores:
print(name)
To get values as well, loop over .items() and unpack both at once — the tuple unpacking from
lesson 3.4:
scores = {"ada": 90, "grace": 95}
for name, score in scores.items():
print(f"{name}: {score}")
This is the most common way to walk a dictionary. If you only need the values, use .values():
scores = {"ada": 90, "grace": 95}
total = 0
for score in scores.values():
total += score
print(total)
That is the accumulator pattern from Module 2, applied to a dictionary.
Useful built-ins
sum(), max(), min(), and len() all work on .values():
scores = {"ada": 90, "grace": 95, "alan": 88}
print(sum(scores.values()))
print(max(scores.values()))
print(len(scores))
Other methods
defaults = {"theme": "dark", "font": "mono"}
custom = {"font": "serif"}
defaults.update(custom)
print(defaults)
.update() merges another dictionary in, overwriting any keys that clash.
scores = {"ada": 90}
scores.setdefault("grace", 0)
scores.setdefault("ada", 0)
print(scores)
.setdefault(key, value) sets the key only if it isn't already there — handy for
initialising a counter without clobbering an existing count.
Counting with a dictionary
Putting it together — this is the standard way to count occurrences of anything:
word = "banana"
counts = {}
for letter in word:
counts[letter] = counts.get(letter, 0) + 1
print(counts)
counts.get(letter, 0) returns the current count, or 0 the first time a letter appears.
Try it yourself
Sum all the values in the dictionary, then print how many entries it has.
Checkpoint
- Looping a dictionary directly iterates its keys.
for k, v in d.items()is the standard way to get both at once.sum(),max(),min()work on.values().d.get(key, 0) + 1is the idiomatic counting pattern.
Questions about this lesson
Log in to ask a question.