How to Loop Through a Dictionary in Python
for key, value in my_dict.items(): to loop over keys and values together. Loop over my_dict (or .keys()) for keys only and .values() for values only.A dictionary stores pairs, so there are three things you might want to loop over: the keys, the values, or both at once. Which one you pick changes what the loop variable contains.
Python 3.7 and newer iterate in insertion order, so you get the items in the order they were added. This page covers the three loops, sorted loops, and the error you get if you change the dictionary while looping.
| Keys and values | for k, v in d.items(): |
|---|---|
| Keys only | for k in d: or d.keys() |
| Values only | for v in d.values(): |
| Order | Insertion order (Python 3.7+) |
| Do not | Add or delete keys while looping over the same dictionary |
Loop through keys and values together with items()
Loop through only the keys or only the values
A plain for key in d: already goes over keys, so .keys() is optional. When you do not need the keys, values() is clearer and avoids a lookup per item.
stock = {"pen": 40, "ink": 5, "book": 12}
for name in stock:
print(name)
print(sum(stock.values()))Loop in sorted order
Wrap the dictionary or its items in sorted() to control the order. Sorting by key is the default for pairs; use key= to sort by value (more in sort a dictionary by value).
stock = {"pen": 40, "ink": 5, "book": 12}
for name in sorted(stock):
print(name, stock[name])
for name, qty in sorted(stock.items(), key=lambda kv: kv[1]):
print(name, qty)
Do not change the dictionary size while looping
Adding or removing keys during a loop raises RuntimeError: dictionary changed size during iteration. Loop over a copy of the keys, list(d), or build a new dictionary. Changing the value of an existing key is safe.
Which dictionary loop should you use?
| You need | Loop | Loop variable holds |
|---|---|---|
| Keys and values | for k, v in d.items() | A key and its value |
| Only keys | for k in d | Each key |
| Only values | for v in d.values() | Each value |
| Position as well | for i, (k, v) in enumerate(d.items()) | Index, key, value |
| Sorted keys | for k in sorted(d) | Each key, alphabetical |
Examples you can run
Press Run, then edit the code and run it again.
Print every key and value
Unpack each pair into two names.
scores = {"Asha": 82, "Ben": 91, "Chen": 75}
for name, score in scores.items():
print(f"{name}: {score}")Expected outputAsha: 82
Ben: 91
Chen: 75
Total all values
When you only need the numbers, loop over values().
cart = {"pen": 2, "book": 15, "ink": 4}
total = 0
for price in cart.values():
total += price
print(total)Expected output21
Number the entries with enumerate()
Wrap items() in enumerate() and unpack with parentheses.
scores = {"Asha": 82, "Ben": 91}
for i, (name, score) in enumerate(scores.items(), start=1):
print(i, name, score)Expected output1 Asha 82
2 Ben 91
Safely remove keys while looping
Iterate over a copy of the keys so the dictionary can change.
stock = {"pen": 40, "ink": 0, "book": 12, "glue": 0}
for name in list(stock):
if stock[name] == 0:
del stock[name]
print(stock)Expected output{'pen': 40, 'book': 12}
Common mistakes
Unpacking a dictionary directly
✗ Wrong
scores = {"Asha": 82}
for name, score in scores:
print(name, score)✓ Right
scores = {"Asha": 82}
for name, score in scores.items():
print(name, score)Looping over a dictionary gives only keys. Call .items() to get pairs.
Deleting keys during the loop
✗ Wrong
d = {"a": 0, "b": 1}
for k in d:
if d[k] == 0:
del d[k]✓ Right
d = {"a": 0, "b": 1}
d = {k: v for k, v in d.items() if v != 0}Loop over list(d) or build a new dictionary with a comprehension.
Expecting the value from a plain loop
✗ Wrong
prices = {"pen": 2}
for p in prices:
print(p + 1)✓ Right
prices = {"pen": 2}
for p in prices.values():
print(p + 1)p is the key. Use prices.values() or prices[p] to reach the value.
How to Loop Through a Dictionary in Python: questions people ask
How do I loop through a dictionary in Python?
Use for key, value in my_dict.items():. It gives you each key together with its value on every iteration.
Is a Python dictionary ordered when I loop over it?
Yes. Since Python 3.7 dictionaries iterate in the order the keys were first inserted.
How do I loop through a dictionary in sorted order?
Use for key in sorted(my_dict): for key order, or sorted(my_dict.items(), key=lambda kv: kv[1]) for value order.
Keep learning
Step-by-step lessons:
Python DictionariesPython for LoopsPython Dictionary Methods
Related:
Python Dictionary items() MethodPython Dictionary keys() MethodPython Dictionary values() MethodHow to Sort a Dictionary by Value in PythonPython enumerate() Function
More in lists, dicts and sets:
How to Remove Duplicates from a List in PythonHow to Sort a Dictionary by Value in PythonHow to Merge Two Dictionaries in PythonHow to Reverse a List in PythonHow to Flatten a List of Lists in PythonHow to Check if a List Is Empty in PythonHow to Get the Last Element of a List in PythonHow to Count Occurrences in a List in Python See all →