Iterate over a Python dictionary with a for loop
Choose keys, values, or items, preserve insertion-order expectations, and avoid changing a dictionary’s keys during iteration.
Use for key, value in mapping.items() when you need both parts of each entry. Iterating over the dictionary itself yields its keys; values() yields only values.
mapping = {"a": 1, "b": 2, "c": 3}
for key in mapping:
print(key, mapping[key])
for key, value in mapping.items():
print(key, value)
for value in mapping.values():
print(value)
Iteration order
Insertion order is guaranteed by the language from Python 3.7 onward; it was a CPython implementation detail in 3.6. Updating an existing key's value does not move that key. Removing a key and inserting it again places it at the end.
Change values carefully; avoid adding or deleting keys
Adding or removing entries while iterating over a dictionary view can raise RuntimeError or prevent a complete traversal. Build a list of keys first when you need to delete entries:
mapping = {"a": 1, "b": -2, "c": 3}
for key in list(mapping):
if mapping[key] < 0:
del mapping[key]
print(mapping) # {'a': 1, 'c': 3}
Or produce a filtered dictionary:
filtered = {key: value for key, value in mapping.items() if value >= 0}
The comprehension creates a new outer dictionary and leaves the original mapping intact. It does not deep-copy mutable values. Replacing values for existing keys is allowed during iteration when the key set stays unchanged, although other code or concurrent mutation can complicate that guarantee.
FAQ
Is keys() different from direct iteration? Both yield keys. keys() returns a dynamic view that also supports set-like operations, such as first.keys() & second.keys().
How do I sort the traversal? Use for key in sorted(mapping) for key order. To sort by values:
for key, value in sorted(mapping.items(), key=lambda item: item[1]):
print(key, value)
The selected values or keys must be mutually orderable, or you must supply a key function that makes them so. Sorting returns a new list; it does not reorder the dictionary itself.
Are items() and values() snapshots? No. They are views of the dictionary. Use list(mapping.items()) when you need a separate list of the current entries; contained objects still remain shared references.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan