How to Iterate Through a Dictionary in Python
What you’ll build or solve
You’ll iterate through a Python dictionary to read keys, values, or both at the same time.
When this approach works best
This approach works best when you:
Learn Python on Mimo
- Need to process key-value data like settings, counters, or user profiles.
- Want to transform a dictionary into a new structure, like a filtered dictionary or a list of results.
- Need to print, validate, or export dictionary contents in a consistent way.
Avoid this approach when:
- You need items ranked or sorted by value. Sort first, then iterate.
Prerequisites
- Python installed
- You know what a dictionary is
Step-by-step instructions
1) Loop over keys (default behavior)
When you iterate over a dictionary directly, you get keys.
scores= {"Mina":90,"Sam":82,"Ada":95}
fornameinscores:
print(name)
This is the same as:
fornameinscores.keys():
print(name)
2) Use the key to read the value
If you have the key, you can access the value with bracket lookup.
scores= {"Mina":90,"Sam":82,"Ada":95}
fornameinscores:
score=scores[name]
print(name,score)
3) Loop over values with .values()
Use .values() when you only care about the values.
scores= {"Mina":90,"Sam":82,"Ada":95}
forscoreinscores.values():
print(score)
This is common for totals and averages:
scores= {"Mina":90,"Sam":82,"Ada":95}
total=0
forscoreinscores.values():
total+=score
print(total)
4) Loop over key-value pairs with .items()
Use .items() when you need both key and value.
scores= {"Mina":90,"Sam":82,"Ada":95}
forname,scoreinscores.items():
print(name,score)
Examples you can copy
Example 1: Print all settings as key=value
Python
settings= {"theme":"dark","language":"en","notifications":True}
forkey,valueinsettings.items():
print(f"{key}={value}")
Example 2: Filter a dictionary while iterating
prices= {"pen":1.2,"notebook":4.5,"backpack":29.0,"eraser":0.8}
expensive= {}
foritem,priceinprices.items():
ifprice>=5:
expensive[item]=price
print(expensive)
Example 3: Build a list from dictionary data
users= {"Naomi":"Boston","Sam":"New York","Ada":"Los Angeles"}
boston_users= []
forname,cityinusers.items():
ifcity=="New York":
boston_users.append(name)
print(boston_users)
Example 4: Iterate in sorted order
By keys (alphabetical):
scores= {"Mina":90,"Sam":82,"Ada":95}
fornameinsorted(scores):
print(name,scores[name])
By values (highest first):
forname,scoreinsorted(scores.items(),key=lambdap:p[1],reverse=True):
print(name,score)
Common mistakes and how to fix them
Mistake 1: Unpacking the wrong thing
What you might do:
scores= {"Mina":90,"Sam":82}
forname,scoreinscores:
print(name,score)
Why it breaks: Iterating over a dictionary yields keys, not (key, value) pairs, so Python cannot unpack the key into two variables.
Correct approach: Use .items().
scores= {"Mina":90,"Sam":82}
forname,scoreinscores.items():
print(name,score)
Mistake 2: Changing the dictionary while iterating over it
What you might do:
scores= {"Mina":90,"Sam":82,"Ada":95}
fornameinscores:
ifscores[name]<90:
delscores[name]
Why it breaks: Modifying a dictionary during iteration can raise RuntimeError and can skip items.
Correct approach: Iterate over a copy of keys.
scores= {"Mina":90,"Sam":82,"Ada":95}
fornameinlist(scores.keys()):
ifscores[name]<90:
delscores[name]
print(scores)
Troubleshooting
If you see ValueError: not enough values to unpack, do this: make sure you’re using .items() when you write for key, value in ....
If you see RuntimeError: dictionary changed size during iteration, do this: iterate over list(d) or list(d.keys()) before deleting or adding keys.
If you see KeyError inside the loop, do this: check that the key exists, or use d.get(key) when keys come from external data.
If you only need values, do this: use .values() to avoid extra lookups.
If you only need keys, do this: loop over the dictionary directly.
Quick recap
- Loop over keys with
for key in d(ord.keys()). - Use the key to access values with
d[key]. - Loop over values with
for value in d.values(). - Loop over key-value pairs with
for key, value in d.items(). - Don’t add or delete keys while iterating. Iterate over a copy of keys if you need to modify the dictionary.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot