Python Iterate Dictionary: Methods and Pitfalls
python iterate dictionary: Learn the correct ways to iterate over Python dictionaries, including key, value, and item access, order guarantees, and safe modification.
When you need to python iterate dictionary, the default loop behavior might not be what you expect. In Python, iterating over a dictionary directly yields its keys, not its values. This article covers the standard iteration patterns, how to access values, the guaranteed insertion order, and what happens when you modify a dictionary during iteration.
The Default Iteration Behavior
When you write a for loop over a dictionary, you get keys:
data = {"name": "Alice", "age": 30, "city": "Paris"} for key in data: print(key)
This is the most common pattern and often sufficient when you only need keys. But if you need the values, you can use data[key] inside the loop, which adds an extra lookup. That works but is less efficient than using .items() directly.
Iterating Over Key-Value Pairs With items()
The dict.items() method returns a view of key-value pairs. You can unpack them directly in the loop:
for key, value in data.items(): print(f"{key}: {value}")
This is the clearest and most efficient way to access both key and value. The view reflects the dictionary's current state, so if the dictionary changes size, the view behavior may raise a runtime error (covered later). Use this method when you need both components.
Using keys() and values() for Explicit Access
Sometimes you only need keys or only values. dict.keys() and dict.values() return views that support iteration and membership tests. For example:
for value in data.values(): print(value) for key in data.keys(): print(key)
Note that data.keys() is equivalent to iterating over the dictionary directly, but it makes the intent explicit. data.values() is the only way to iterate over values without indexing. These views are dynamic: they reflect changes to the dictionary, but you cannot modify the dictionary's size while iterating.
Iteration Order and Python Version Behavior
Since Python 3.7, dictionaries preserve insertion order as a language guarantee. Before that, it was an implementation detail in CPython 3.6. This means the order you see when iterating is the order in which keys were added. This is important when order matters, such as when building configuration objects or processing data in a specific sequence.
If you need sorted iteration, you can pass the keys to sorted():
for key in sorted(data): print(key, data[key])
Or use sorted(data.items()) to sort by key. Sorting by value requires a custom key function.
Modifying a Dictionary While Iterating
Attempting to add or remove keys while iterating over a dictionary raises a RuntimeError: dictionary changed size during iteration. This is a protection against undefined behavior. For example:
for key in data: if key == "age": del data[key] # RuntimeError
If you need to filter a dictionary, build a new dictionary or collect keys to delete first. A common pattern is to iterate over a list of keys:
for key in list(data.keys()): if condition(key): del data[key]
Using list() creates a snapshot, so the dictionary can be safely modified. Alternatively, use a dictionary comprehension to create a filtered copy.
Performance and Memory Considerations
The iteration methods return views, not lists, so they avoid copying the entire dictionary. This is efficient for large dictionaries. However, indexing with data[key] inside a loop is slightly slower than using .items() because it performs a hash lookup for each iteration. If you need both key and value, .items() is the fastest and most readable option.
Memory usage is minimal because views are lazy. But if you convert a view to a list, you allocate memory for all elements. Only do that when you need a snapshot or random access.
Choosing the Right Iteration Method
The choice depends on what you need in the loop:
- Use direct iteration when you only need keys.
- Use
.items()when you need both key and value. - Use
.values()when you only need values. - Use
.keys()when you want to make the key iteration explicit or need a view for membership tests.
For nested dictionaries, you may need to iterate over outer keys and then access inner dictionaries. The same principles apply.