Python Dictionary Foreach: Iterate Keys, Values, Pairs
Learn how to use Python for loops to iterate over dictionary keys, values, and key-value pairs, and modify dictionaries safely.

Python doesn't have a dedicated foreach keyword, but its for loop gives you the same ability to iterate over a dictionary. The default behavior of for over a dictionary is to yield its keys. Use .items() for key-value pairs, .keys() for keys only, and .values() for values only. Choose the method based on what you need, and avoid adding or removing keys while iterating.
Iterating Over Keys
config = {"host": "localhost", "port": 8080, "debug": True}
for key in config:
print(key)Because dictionaries are iterable, a plain for loop iterates over their keys. In Python 3.7 and later, the iteration order is insertion order, so this loop prints host, port, and debug. To get the value for each key, use config[key] inside the loop; when you need both key and value, items() is more direct.
Iterating Over Key-Value Pairs with items()
for key, value in config.items():
print(f"{key}: {value}")items() returns a dictionary view of (key, value) pairs. Unpacking the pairs in the for loop gives you both components without a separate lookup.
The view is dynamic: if you update an existing key's value during iteration, the view reflects the new value. However, adding or removing keys while iterating can raise RuntimeError or skip entries, so avoid it.
Iterating Over Keys or Values Separately
for key in config.keys():
print(key)
for value in config.values():
print(value)Using config.keys() is equivalent to iterating over config directly, but it makes the intent explicit. Use config.values() when you need only the values and do not want to handle keys.
Modifying a Dictionary While Iterating
This pattern is unsafe; it often raises RuntimeError: dictionary changed size during iteration.
# May raise RuntimeError: dictionary changed size during iteration
for key in config:
if key == "port":
del config[key]The safe way to remove entries is to iterate over a snapshot of the keys:
for key in list(config.keys()):
if key == "port":
del config[key]list(config.keys()) creates a list copy before iteration starts, so deletions from the original dictionary do not affect the loop. Another safe pattern is to collect the keys you want to remove and delete them after the loop.
Assigning a new value to an existing key during iteration is safe because it does not change the dictionary's size. Adding new keys or deleting keys while iterating can cause the runtime error or skipped entries.
Performance and Memory Considerations
The items(), keys(), and values() methods return view objects, not lists. Iterating over them avoids creating a separate list of entries, which keeps memory use lower for large dictionaries. If you call list(config.items()) or list(config.keys()), you materialize the entries into a list; use that only when you need a snapshot or an actual list.
Iteration order is insertion order in Python 3.7 and later. If you need a different order, sort the keys or items before iterating instead of relying on dictionary order.
Building New Dictionaries with Comprehensions
Dictionary comprehensions provide a concise way to build a new dictionary by iterating over an existing one.
original = {"a": 1, "b": 2, "c": 3}
squared = {k: v ** 2 for k, v in original.items()}You can also filter items with a condition at the end:
even = {k: v for k, v in original.items() if v % 2 == 0}This pattern is idiomatic and often more readable than manually building a dictionary in a loop.
Choosing the Right Data Structure
If insertion order is not the order you need, sort the keys or items before iterating:
for key in sorted(config):
print(key, config[key])collections.OrderedDict preserves insertion order just like a regular dict in Python 3.7 and later, so it does not provide a different iteration order. Use a standard dict unless you need one of OrderedDict's extra methods or support for older Python versions. If you often need positional access to pairs and do not need dictionary semantics, a list of tuples may be simpler.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.