How to Loop Through a Dictionary in Python
Learn how to loop through Python dictionaries with items(), keys(), and values(), unpack key-value pairs, sort entries, and safely delete items while iterating.
A Python dictionary is a mutable mapping that connects unique keys to values. A key is the identifier used to retrieve data, and a value is the data associated with that key. Together, one key and its value form a key-value pair.
A for loop can visit dictionary data one entry at a time. Each pass through the loop is called an iteration.
Loop Through Key-Value Pairs with items()
Use the dictionary items() method when you need both the key and its matching value. The standard pattern is:
for key, value in data.items():
# use key and value here
items() returns a dynamic view of the dictionary's key-value pairs in modern Python. The two variables in the for statement receive the two parts of each pair.
How Tuple Unpacking Works
Each item supplied by items() behaves like a two-element tuple: the key comes first and the value comes second. Python assigns those elements to the two loop variables. This is called tuple unpacking.
| Concept | Meaning | Example |
|---|---|---|
| key | The unique identifier used to retrieve a value. | "eye_color" |
| value | The data associated with a key. | "blue" |
| key-value pair | One dictionary entry containing a key and its corresponding value. | ("eye_color", "blue") |
| tuple unpacking | Assigning separate elements to multiple variables in one operation. | for key, value in data.items() |
Read the Loop Variables
During each iteration, the first loop variable represents the key and the second represents the value. You can print them, compare them, calculate with them, or use them in another operation inside the loop.
person = {"eye_color": "blue", "height": "165cm", "weight": "54kg"}
for key, value in person.items():
print("Key:", key, "Value:", value)
For the first entry, key receives "eye_color" and value receives "blue". The same assignment happens again for every remaining entry.
Use Descriptive Variable Names
k and v are common short names for key and value, but they are only naming conventions. Python does not require those names. Choose names that make the code easy to understand.
settings = {"theme": "dark", "font_size": 16}
for setting_name, setting_value in settings.items():
print(f"{setting_name}: {setting_value}")
Names such as setting_name and setting_value are often clearer than k and v. For example, attribute and measurement can describe a dictionary containing measured attributes.
Dictionary Iteration Order
Python dictionaries preserve insertion order in Python 3.7 and later. Normal iteration follows the order in which entries were added; it does not automatically sort keys alphabetically.
scores = {"Noah": 88, "Ava": 92}
for student, score in scores.items():
print(student, score)
This loop visits "Noah" before "Ava" because that is their insertion order. If you explicitly need key-sorted traversal, use sorted():
scores = {"Noah": 88, "Ava": 92}
for student, score in sorted(scores.items()):
print(student, score)
Here, sorted(scores.items()) sorts the key-value pairs by key by default.
Alternative Dictionary Iteration Patterns
When you loop directly over a dictionary, Python yields its keys. Use keys() for explicit key iteration, values() for value-only iteration, and items() when both parts are needed.
| Syntax | Loop variable receives | Best use case |
|---|---|---|
for key in data | Each key | Simple key iteration |
for key in data.keys() | Each key | Explicitly communicating that only keys are needed |
for value in data.values() | Each value | Processing values when keys are not needed |
for key, value in data.items() | Each key and matching value | Using both parts of every dictionary entry |
Loop Over Keys
scores = {"Ava": 92, "Noah": 88}
for student in scores:
print(student)
The direct form is equivalent in purpose to for student in scores.keys(). Both loops provide keys.
Loop Over Values
scores = {"Ava": 92, "Noah": 88}
for score in scores.values():
print(score)
Use values() when the keys are not relevant to the operation.
Do Not Change Dictionary Size During Direct Iteration
Avoid adding or removing entries while directly iterating over a dictionary. Changing its size while the loop is active can raise a RuntimeError because Python cannot safely continue the current iteration.
scores = {"Ava": 92, "Noah": 48, "Mia": 76}
for student, score in list(scores.items()):
if score < 50:
del scores[student]
list(scores.items()) creates a separate list of the entries. The loop reads that fixed list while the original dictionary is changed. After the loop, scores contains only entries whose scores are at least 50.
You can use the same technique when deleting based on keys:
for key in list(data.keys()):
if should_remove(data[key]):
del data[key]
Adding entries also changes the dictionary size, so build a separate list of changes first or iterate over a copied list when structural changes are required.
Common Problems and Fixes
Trying to Unpack Two Variables Directly
for key, value in data:
print(key, value)
This fails because direct dictionary iteration produces one key at a time, not a key-value pair. If a key is a string or another iterable, Python may also produce an unpacking-related error depending on its contents.
Use items() when both parts are required:
for key, value in data.items():
print(key, value)
Only Keys Appear
for item in data:
print(item)
The variable item receives each key because that is the default dictionary iteration behavior. Use data.values() for values only or data.items() for both keys and values.
Output Is Not Alphabetical
Insertion order and alphabetical order are different. Modern Python preserves insertion order, but it does not sort a dictionary automatically. Use sorted(data.items()) for key-sorted output.
A Runtime Error Appears After Deletion
for key, value in data.items():
del data[key]
This resizes the dictionary during active iteration. Iterate over list(data.items()) or list(data.keys()) instead.
Quick Reference
- Use
for key, value in data.items():for key-value pairs. - Use
for key in data:ordata.keys()for keys. - Use
for value in data.values():for values. - Remember that
items()supplies pairs that Python can unpack into two variables. - Expect insertion order in Python 3.7 and later, not automatic alphabetical order.
- Use
sorted(data.items())when sorted key order is required. - Iterate over a copied list before adding or removing dictionary entries.
To review related fundamentals, see what dictionaries are, Python for loops, and Python variable names.