Going Through Every Key and Value
The problem...
You have a dict with ten entries. Twenty. A hundred.
You need to do something with every key, every value, or every pair.
Writing it out manually isn't an option.
The idea!
You can loop over a dict just like you loop over a list.
The difference: a dict has keys and values. You choose what you loop over.
Looping over keys — default behavior
A for loop on a dict gives you the keys by default:
scores = {"Raven": 85, "Wolf": 74, "Ghost": 91}
for key in scores:
print(key)
Output:
Raven
Wolf
Ghost
Same as looping over scores.keys() — explicit version:
for key in scores.keys():
print(key)
Looping over values
scores = {"Raven": 85, "Wolf": 74, "Ghost": 91}
for value in scores.values():
print(value)
Output:
85
74
91
Looping over key-value pairs
items() gives you both at once — this is what you'll use most:
scores = {"Raven": 85, "Wolf": 74, "Ghost": 91}
for name, score in scores.items():
print(f"{name}: {score}")
Output:
Raven: 85
Wolf: 74
Ghost: 91
Python unpacks each pair into two variables — the key goes to the first, the value to the second.
Doing something with each pair
scores = {"Raven": 85, "Wolf": 74, "Ghost": 91}
for name, score in scores.items():
if score >= 80:
print(f"{name} — passed")
Output:
Raven — passed
Ghost — passed
Building a new dict from a loop
Start with an empty dict and populate it as you go:
scores = {"Raven": 85, "Wolf": 74, "Ghost": 91}
passing = {}
for name, score in scores.items():
if score >= 80:
passing[name] = score
print(passing)
Output → {'Raven': 85, 'Ghost': 91}
What's really happening
A for loop on a dict moves through its keys in insertion order.
.values() and .items() give you different slices of the same data.
The dict is never modified by the loop itself.
Heads up!
- Looping directly over a dict gives you keys — not values, not pairs
- Use
.items()when you need both key and value — it's the most common pattern - Don't modify a dict while looping over it — results are unpredictable
- Variable names in
for key, value in d.items()are yours — pick readable ones
The mindset shift
Stop thinking: "I need to look up each key manually."
Start thinking: "I loop over the dict and Python hands me each pair directly."
What you should understand now
- Looping over a dict directly gives you keys
- Use
.values()to loop over values only - Use
.items()to loop over key-value pairs — the most useful pattern - Python unpacks each pair into two variables automatically
- Don't modify a dict while looping over it