There are three ways to loop over a dictionary depending on what you need: only the keys, only the values, or both at once.
grades = {"ana": 9, "luis": 6, "eva": 7}
Looping over the keys
A for over the dictionary goes through its keys. With .keys() the result is the same, but it is more explicit:
for name in grades:
print(name)
# ana
# luis
# eva
for name in grades.keys(): # equivalent
print(name)
Looping over the values
for grade in grades.values():
print(grade)
# 9
# 6
# 7
print(sum(grades.values())) # 22
print(max(grades.values())) # 9
Looping over key and value at once
The items() method gives each pair as a (key, value) tuple, which you can unpack directly in the for:
for name, grade in grades.items():
print(f"{name}: {grade}")
# ana: 9
# luis: 6
# eva: 7
Looping in order
To go through the keys sorted, use sorted():
for name in sorted(grades):
print(name, grades[name])
# ana 9
# eva 7
# luis 6
To sort by value, sort a list of tuples by turning them around (value first):
pairs = []
for name, grade in grades.items():
pairs.append((grade, name))
pairs.sort(reverse=True)
print(pairs) # [(9, 'ana'), (7, 'eva'), (6, 'luis')]
Do not modify the dictionary while looping over it
Adding or deleting keys inside the for that loops over that same dictionary causes an error:
for name in grades:
grades[name + "2"] = 0
# RuntimeError: dictionary changed size during iteration
If you need to, loop over a copy of the keys with list(grades) or build a new dictionary.
Useful methods
| Method | What it does |
|---|---|
d.keys() | the keys |
d.values() | the values |
d.items() | the (key, value) pairs |
len(d) | how many pairs there are |
d.get(k, x) | the value of k, or x if it does not exist |
d.pop(k) | removes k and returns its value |
d.clear() | empties the dictionary |
Practice in Average per student and Reverse translator.