How to Iterate Over Dictionary in Python: Syntax and Examples
To iterate over a dictionary in Python, use a
for loop with dict.keys() to access keys, dict.values() for values, or dict.items() to get both keys and values together. This lets you process each element in the dictionary easily.Syntax
You can loop through a dictionary in three main ways:
- Keys only:
for key in dict.keys(): - Values only:
for value in dict.values(): - Keys and values:
for key, value in dict.items():
Each method lets you access different parts of the dictionary during iteration.
python
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Iterate keys
for key in my_dict.keys():
print(key)
# Iterate values
for value in my_dict.values():
print(value)
# Iterate keys and values
for key, value in my_dict.items():
print(f"{key}: {value}")Output
a
b
c
1
2
3
a: 1
b: 2
c: 3
Example
This example shows how to print all keys, all values, and both keys and values from a dictionary.
python
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print('Keys:')
for key in person.keys():
print(key)
print('\nValues:')
for value in person.values():
print(value)
print('\nKeys and Values:')
for key, value in person.items():
print(f'{key} -> {value}')Output
Keys:
name
age
city
Values:
Alice
30
New York
Keys and Values:
name -> Alice
age -> 30
city -> New York
Common Pitfalls
One common mistake is trying to modify a dictionary while iterating over it, which can cause errors or unexpected behavior. Also, using for key in dict: works but is less explicit than dict.keys(). Forgetting to unpack key, value when using dict.items() will cause errors.
python
my_dict = {'x': 10, 'y': 20}
# Wrong: modifying dict during iteration
# for key in my_dict:
# if key == 'x':
# del my_dict[key] # This causes RuntimeError
# Right: iterate over a copy to modify safely
for key in list(my_dict.keys()):
if key == 'x':
del my_dict[key]
print(my_dict)Output
{'y': 20}
Quick Reference
Use these methods to iterate over a dictionary:
| Method | Description | Example |
|---|---|---|
dict.keys() | Iterate over keys only | for k in dict.keys(): |
dict.values() | Iterate over values only | for v in dict.values(): |
dict.items() | Iterate over keys and values | for k, v in dict.items(): |
Key Takeaways
Use
dict.items() to get both keys and values in a loop.Avoid changing a dictionary while iterating over it directly.
You can iterate keys with
dict.keys() and values with dict.values().Unpack keys and values properly when using
dict.items().Iterating directly over the dictionary loops over keys by default.