VMware ESXi and vSphere Cluster Management
How to Loop Through a Dictionary in Python
Learn how to loop through Python dictionaries with for loops, including items(), keys(), values(), unpacking, examples, and troubleshooting.
A Python dictionary is a mutable mapping that associates unique keys with values. A key is the identifier used to look up data, and a value is the data associated with that key. Together, a key and its value form a key-value pair.
A for loop can visit dictionary data one entry at a time. This is useful when your code needs to process both the label and the associated data, such as displaying a profile attribute and its value or checking product quantities.
Loop Through Key-Value Pairs with items()
The standard way to iterate over both parts of each dictionary entry is the items() method. For a dictionary named my_dict, use this pattern:
for key, value in my_dict.items():
print(key, value)
my_dict.items() provides an iterable view of the dictionary's key-value pairs. During each iteration, which means one pass through the loop, one pair is assigned to the two loop variables.
The two variables use tuple unpacking. Each pair contains two elements: the first element is assigned to key, and the second element is assigned to value.
| Pair from items() | First loop variable | Second loop variable |
|---|---|---|
('height', '165cm') | key receives 'height' | value receives '165cm' |
Read Keys and Values Inside the Loop
Consider a dictionary containing profile attributes:
profile = {
"eye_color": "blue",
"height": "165cm",
"weight": "54kg"
}
for key, value in profile.items():
print(f"{key}: {value}")
The loop body runs once for every dictionary entry. The variables change on each iteration, so the output is:
eye_color: blue
height: 165cm
weight: 54kg
The fixed text, such as the colon and space in the f-string, is combined with the current key and value. You can also use the variables in conditions, calculations, function calls, or other processing logic.
Practical Example: Display Product Inventory
This inventory dictionary maps product names to quantities:
inventory = {
"notebook": 12,
"pen": 30,
"eraser": 8
}
for product, quantity in inventory.items():
print(f"{product}: {quantity} in stock")
Here, product receives each key and quantity receives its associated value. The result is:
notebook: 12 in stock
pen: 30 in stock
eraser: 8 in stock
Choosing Loop Variable Names
Loop variable names are chosen by the programmer. They do not change how the dictionary works. The common short names k and v are valid:
for k, v in inventory.items():
print(k, v)
However, key and value, or descriptive names such as product and quantity, are usually clearer for beginners and for anyone reading the code later.
Dictionary Iteration Order
Modern Python dictionaries preserve insertion order. This means entries are normally visited in the order in which they were added. For example, a dictionary created with "first" followed by "second" will normally produce those keys in that order when iterated.
Do not assume that an older Python version or unordered external data will use the same order. If a sorted presentation is required, sort the keys explicitly instead of relying on insertion order:
scores = {
"Zoe": 91,
"Adam": 88,
"Mia": 95
}
for name in sorted(scores):
print(name, scores[name])
Other Dictionary Iteration Patterns
Python provides several ways to traverse a dictionary. The main focus for processing complete entries is items(), but these related forms are useful:
| Expression | What each loop iteration returns | Best use case |
|---|---|---|
for key in data | One key | Iterating directly over keys; this is the default dictionary behavior |
for key in data.keys() | One key | Explicitly communicating that only keys are needed |
for value in data.values() | One value | Processing values without needing their keys |
for key, value in data.items() | One key-value pair | Processing both the key and its associated value |
Iterating Directly Over a Dictionary
When you loop over a dictionary without calling a method, Python yields its keys:
language_info = {
"language": "Python",
"level": "beginner"
}
for key in language_info:
print(key)
This prints:
language
level
To obtain a value from each key, use dictionary lookup:
for key in language_info:
print(key, language_info[key])
Although this works, items() is usually more direct when both the key and value are needed:
for key, value in language_info.items():
print(key, value)
Iterating Over Keys or Values Explicitly
Use keys() when only keys are relevant:
for key in language_info.keys():
print(key)
Use values() when only values are relevant:
for value in language_info.values():
print(value)
Comparing the Loop Forms
With the same dictionary, these loops expose different data:
data = {
"language": "Python",
"level": "beginner"
}
# Keys only
for key in data:
print(key)
# Values only
for value in data.values():
print(value)
# Keys and values
for key, value in data.items():
print(f"{key} = {value}")
Choose the form that matches the information your loop body needs. If both components of each mapping are required, use items().
Troubleshooting Dictionary Loops
ValueError When Unpacking
This loop is incorrect when you expect two variables:
for key, value in my_dict:
print(key, value)
A direct dictionary loop yields one key at a time. Python then tries to unpack that single key into key and value, which can cause a ValueError. Use items() instead:
for key, value in my_dict.items():
print(key, value)
Only Keys Are Printed
If this code prints only keys:
for item in my_dict:
print(item)
the cause is that direct dictionary iteration returns keys. Use items() for both keys and values, or values() for values only:
for value in my_dict.values():
print(value)
Unexpected Output Order
Check the order in which entries were inserted. In supported modern Python versions, insertion order is preserved, but the dictionary may have been created or updated in an order different from what you expected. For a sorted display, use sorted() on the keys.
Syntax or Indentation Errors
A for statement needs a colon, and every statement belonging to the loop must be indented:
for key, value in my_dict.items():
print(key, value)
Forgetting the colon or indentation can produce a syntax or indentation error.
Key Takeaways
- A dictionary stores unique keys mapped to values.
- A for loop visits dictionary data one entry at a time.
- Use
for key, value in dictionary.items():when both parts of each entry are needed. items()provides pairs, and tuple unpacking assigns their two elements to separate variables.- Looping directly over a dictionary yields keys.
- Use
keys()for explicit key iteration andvalues()for value-only iteration. - Modern Python dictionaries preserve insertion order, but sort keys explicitly when sorted output is required.