To iterate over a dictionary in Python using a for
loop, you can use the following methods depending on what you want to access: keys, values, or both key-value pairs. Here’s how to do it:
1. Iterate Over Keys Only
By default, iterating over a dictionary loops through its keys:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
print(key) # Output: 'a', 'b', 'c'
# Explicitly using .keys() (same result)
for key in my_dict.keys():
print(key)
2. Iterate Over Values Only
Use .values()
to loop through values:
for value in my_dict.values():
print(value) # Output: 1, 2, 3
3. Iterate Over Key-Value Pairs
Use .items()
to loop through keys and values together (most common):
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
# Output:
# Key: a, Value: 1
# Key: b, Value: 2
# Key: c, Value: 3
Key Notes:
.items()
: Returns a list-like object of tuples(key, value)
in Python 3 (or a list in Python 2).- Unpacking: Use
key, value
to unpack the tuple directly in the loop. - Order: Dictionaries preserve insertion order in Python 3.7+. In earlier versions, use
collections.OrderedDict
.
Example: Modify Values During Iteration
You can update dictionary values while iterating:
for key in my_dict:
my_dict[key] *= 2 # Double each value
print(my_dict) # Output: {'a': 2, 'b': 4, 'c': 6}
Edge Cases
- Avoid modifying the dictionary structure (adding/removing keys) during iteration; this may cause errors. Use
list(my_dict.keys())
to iterate over a static list of keys if needed. - Use a dictionary comprehension for efficient transformations:
doubled = {k: v*2 for k, v in my_dict.items()}
Summary
Method | Purpose | Example |
---|---|---|
for key in d | Iterate over keys | print(key) |
d.values() | Iterate over values | print(value) |
d.items() | Iterate over key-value pairs | print(key, value) |
Use .items()
for most use cases where you need both keys and values!