Python Looping Through Dictionaries
What you will learn
- Looping over keys, values and pairs
- Looping in sorted order
- Changing values safely while you loop
- Building a dictionary with a loop, and with a dictionary comprehension
- Filtering, transforming, inverting, counting and grouping
The examples use these made-up scores:
scores = {"Rina": 90, "Sam": 75, "Lee": 82}
1. Looping over a dictionary
A plain for loop gives the keys. Use .values() for the values and .items() for both, as (key, value) pairs (lesson 9.2):
for name in scores:
print(name, end=" ")
print()
for s in scores.values():
print(s, end=" ")
print()
for name, s in scores.items():
print(f"{name}: {s}", end="; ")
print()
Rina Sam Lee
90 75 82
Rina: 90; Sam: 75; Lee: 82;
for name, s in scores.items() unpacks each pair into two names (lesson 8.2). It is the most useful form, because you have the key and the value together. With enumerate, put the pair in brackets:
for i, (name, s) in enumerate(scores.items(), 1):
print(i, name, s, end="; ")
print()
1 Rina 90; 2 Sam 75; 3 Lee 82;
The loop visits the pairs in the order they were added (lesson 9.5).
Quick check: what does `for x in {"a": 1, "b": 2}:` give `x`?
The keys: "a", then "b".
2. Sorted loops
A dictionary has no sorting of its own, but you can loop over a sorted view:
for name in sorted(scores):
print(name, end=" ")
print()
for name, s in sorted(scores.items(), key=lambda p: p[1], reverse=True):
print(name, s, end="; ")
print()
Lee Rina Sam
Rina 90; Lee 82; Sam 75;
sorted(scores)sorts the keys.sorted(scores.items(), key=lambda p: p[1], reverse=True)sorts the pairs by value, biggest first (lesson 7.4).
3. Quick statistics
The built-ins work on the values and keys:
print(round(sum(scores.values()) / len(scores), 1))
print(max(scores, key=scores.get))
print(min(scores.values()))
print(any(v > 85 for v in scores.values()), all(v > 70 for v in scores.values()))
82.3
Rina
75
True True
max(scores, key=scores.get) gives the key with the biggest value (here Rina).
4. Changing values while looping
You may change the value of an existing key inside the loop. What you must not do is add or remove keys (lesson 9.2):
points = {"Rina": 90, "Sam": 75, "Lee": 82}
for name in points:
points[name] += 5
print(points)
{'Rina': 95, 'Sam': 80, 'Lee': 87}
The loop variable itself is only a copy of the reference, so changing it does not change the dictionary:
for key, value in {"x": 10}.items():
key = key.upper()
value += 1
print(key, value)
X 11
The dictionary still holds {"x": 10}. To change a value, assign through the dictionary: d[key] = ....
5. Building a dictionary with a loop
Start with an empty dictionary and add one pair per pass:
doubled = {}
for name, s in scores.items():
doubled[name] = s * 2
print(doubled)
{'Rina': 180, 'Sam': 150, 'Lee': 164}
6. Dictionary comprehensions
A dictionary comprehension builds a dictionary in one line. Its shape is {key: value for item in collection}, with an optional if at the end (chapter 12 covers comprehensions in full):
squares = {n: n * n for n in range(1, 6)}
print(squares)
evens = {n: n * n for n in range(1, 11) if n % 2 == 0}
print(evens)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
The most common use is to transform or filter another dictionary, looping over its .items():
passed = {n: s for n, s in scores.items() if s >= 80}
print(passed)
grades = {n: ("A" if s >= 90 else "B") for n, s in scores.items()}
print(grades)
upper = {k.upper(): v for k, v in scores.items()}
print(upper)
{'Rina': 90, 'Lee': 82}
{'Rina': 'A', 'Sam': 'B', 'Lee': 'B'}
{'RINA': 90, 'SAM': 75, 'LEE': 82}
- Filter: the
ifat the end keeps some pairs. - Transform the values: change the expression after the colon (here with a conditional expression, lesson 5.4).
- Transform the keys: change the expression before the colon.
Removing pairs is easiest this way too. Build a new dictionary without them:
d = {"a": 1, "b": 2, "c": 3}
d = {k: v for k, v in d.items() if v != 2}
print(d)
{'a': 1, 'c': 3}
Building from two lists
words = ["apple", "fig", "kiwi"]
print({w: len(w) for w in words})
print(dict(zip(words, range(3))))
print({i: c for i, c in enumerate("ab")})
{'apple': 5, 'fig': 3, 'kiwi': 4}
{'apple': 0, 'fig': 1, 'kiwi': 2}
{0: 'a', 1: 'b'}
7. Inverting a dictionary
To swap keys and values, loop over the pairs:
inv = {v: k for k, v in {"a": 1, "b": 2}.items()}
print(inv)
{1: 'a', 2: 'b'}
This only works when the values are unique and hashable. If two keys share a value, the later one overwrites the earlier one:
print({v: k for k, v in {"a": 1, "b": 2, "c": 1}.items()})
{1: 'c', 2: 'b'}
The key "a" was lost. To keep them all, collect them in lists:
groups = {}
for k, v in {"a": 1, "b": 2, "c": 1}.items():
groups.setdefault(v, []).append(k)
print(groups)
{1: ['a', 'c'], 2: ['b']}
8. Counting
A dictionary is the standard tool for counting how often things occur. The keys are the things and the values are the counts:
text = "the cat and the hat and the bat"
counts = {}
for w in text.split():
counts[w] = counts.get(w, 0) + 1
print(counts)
print(sorted(counts.items(), key=lambda p: (-p[1], p[0]))[:3])
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
[('the', 3), ('and', 2), ('bat', 1)]
counts.get(w, 0) + 1 is the current count, or 0 the first time. The second line shows the top three: by count, biggest first, then by word. The standard library has a tool just for this, collections.Counter (lesson 9.6).
9. Dictionaries inside loops
When the values are lists, use a nested loop (lesson 6.4):
data = {"fruits": ["apple", "fig"], "veg": ["leek"]}
for group, items in data.items():
for item in items:
print(group, item, end="; ")
print()
print({g: len(i) for g, i in data.items()})
print(sum(len(i) for i in data.values()))
fruits apple; fruits fig; veg leek;
{'fruits': 2, 'veg': 1}
3
Worked example: marks to grades and a class summary
Turn marks into letter grades, count each grade, and find the top student.
marks = {"Rina": 92, "Sam": 67, "Lee": 81, "Mia": 74, "Tom": 88}
def letter(m):
if m >= 90:
return "A"
elif m >= 80:
return "B"
elif m >= 70:
return "C"
return "D"
grades = {name: letter(m) for name, m in marks.items()}
counts = {}
for g in grades.values():
counts[g] = counts.get(g, 0) + 1
print(grades)
print(dict(sorted(counts.items())))
print(max(marks, key=marks.get), round(sum(marks.values()) / len(marks), 1))
{'Rina': 'A', 'Sam': 'D', 'Lee': 'B', 'Mia': 'C', 'Tom': 'B'}
{'A': 1, 'B': 2, 'C': 1, 'D': 1}
Rina 80.4
| Step | Tool |
|---|---|
| marks to grades | a dictionary comprehension that calls letter |
| counting the grades | a loop with get(g, 0) + 1 |
| the top student | max(marks, key=marks.get) |
| the average | sum(...) / len(...) of the values |
The names, marks and grade limits are made up. (def and return are chapter 11.)
Common mistakes
- Adding or removing keys inside a loop over the same dictionary. Build a new dictionary.
- Forgetting
.items()and trying to unpack the keys:for k, v in d:fails for most dictionaries. - Expecting to change values by changing the loop variable. Assign through
d[key]. - Inverting a dictionary with repeated values and losing keys.
- Expecting a sorted dictionary. Sort the keys or pairs in the loop.
Key takeaways
- A
forloop over a dictionary gives keys;.values()gives values;.items()gives(key, value)pairs to unpack. sorted(d)andsorted(d.items(), key=...)loop in a chosen order.- Changing the value of an existing key while looping is fine; adding or removing keys is not.
- A dictionary comprehension
{k: v for ... if ...}transforms and filters in one line. - Count with
d[x] = d.get(x, 0) + 1; group withsetdefault(key, []).append(item); inverting needs unique values.
Practice
1. Print each key and value of {"a": 1, "b": 2} on one line like a=1.
Show answer
for k, v in {"a": 1, "b": 2}.items():
print(f"{k}={v}")
2. Build {1: 1, 2: 4, 3: 9} with a comprehension.
Show answer
{n: n * n for n in range(1, 4)}.
3. Keep only the pairs of prices whose value is under 10.
Show answer
{k: v for k, v in prices.items() if v < 10}.
4. Count how many times each letter appears in "banana".
Show answer
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
The result is {'b': 1, 'a': 3, 'n': 2}.
5. Why does {v: k for k, v in {"a": 1, "b": 1}.items()} lose a key?
Show answer
Both values are 1, so after inverting they are the same key, and the later pair overwrites the earlier one. The result is {1: 'b'}.
6. Print the names of scores from the highest score to the lowest.
Show answer
for name in sorted(scores, key=scores.get, reverse=True):
print(name)