Back to Blog
Python

Python Dictionary Foreach: Iterate Keys, Values, Pairs

python dictionary foreach: Learn how to iterate over Python dictionaries using for loops, items(), keys(), and values(), including safe modification and performance co...

Pythondictionaryiterationitems()performance
Illustration of a Python dictionary iteration loop showing keys and values.

When you search for python dictionary foreach, you're likely looking for the idiomatic way to iterate over a dictionary's contents in Python. Unlike languages with a dedicated foreach keyword, Python uses the for loop combined with dictionary views to achieve the same result. The approach you choose depends on whether you need keys, values, or both, and whether you plan to modify the dictionary during iteration.

The Basic for Loop Over a Dictionary

Writing a for loop directly over a dictionary iterates over its keys. This is the simplest form of a foreach in Python and works because dictionaries are iterable objects that yield keys by default.

config = {"host": "localhost", "port": 8080, "debug": True} for key in config: print(key)

This prints each key in the order they were inserted (in Python 3.7 and later). If you need the corresponding value, you can access it inside the loop with config[key], but that requires an additional lookup. For most cases, the items() method is more direct.

Iterating Over Key-Value Pairs with items()

The items() method returns a view of key-value pairs as tuples. Unpacking these tuples in a for loop gives you both the key and the value in one step, avoiding a separate dictionary lookup.

for key, value in config.items(): print(f"{key}: {value}")

This is the most common and readable way to iterate over a dictionary when you need both components. The view is dynamic, meaning it reflects changes to the dictionary even if you modify it after the loop starts—though modifying the size during iteration is unsafe, as we'll see later.

Iterating Over Keys and Values Separately

Sometimes you only need keys or only values. The keys() and values() methods return views that let you iterate over just one component.

for key in config.keys(): print(key) for value in config.values(): print(value)

Iterating directly over the dictionary is equivalent to iterating over keys(), but using keys() makes the intent explicit and can improve readability. The values() view is useful when you want to process only the values without caring about the keys.

Modifying a Dictionary While Iterating

A common pitfall is adding or removing items while iterating over a dictionary. This raises a RuntimeError because the dictionary's size changes during iteration, which breaks the iterator's internal assumptions.

# This raises RuntimeError: dictionary changed size during iteration for key in config: if key == "port": del config[key]

To modify safely, iterate over a copy of the keys or values. A common pattern is to use list(config.keys()) to create a snapshot before the loop:

for key in list(config.keys()): if key == "port": del config[key]

Alternatively, collect the keys you want to delete and remove them after the loop finishes. This avoids the runtime error and keeps the iteration logic clear.

Performance and Memory Considerations

Dictionary views are lightweight and do not create a separate list of items. Iterating over items() yields tuples on the fly, which is memory-efficient for large dictionaries. In contrast, calling list(config.items()) materializes all pairs into a new list, which can be expensive for big data.

Iteration order is guaranteed to be insertion order in Python 3.7 and later, so you can rely on predictable ordering. If you need to iterate multiple times and the dictionary is large, consider whether a list of keys is more appropriate—especially if you also need random access by index.

When you only need values, values() is slightly faster than items() because it avoids constructing tuples. However, the difference is usually negligible unless you're processing millions of entries.

Using Dictionary Comprehensions for Transformation

Dictionary comprehensions provide a concise way to build a new dictionary by iterating over an existing one. This is often used for filtering or transforming values.

original = {"a": 1, "b": 2, "c": 3} squared = {k: v ** 2 for k, v in original.items()}

You can also filter items by adding 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.

When to Choose a Different Data Structure

While the built-in dictionary is the right choice for most key-value mapping needs, there are cases where another structure is better. If you need to iterate in a specific order that isn't insertion order, consider using collections.OrderedDict (though it's now equivalent to the standard dict) or sorting keys before iteration. If you need to frequently access items by position, a list of tuples might be more suitable.

For scenarios where you need to maintain a mapping and also iterate frequently, the standard dict with items() is usually sufficient. The key is to match the data structure to your access patterns rather than forcing iteration onto an unsuitable container.

python dictionary foreach: Practical Usage and Code Examples | RYUSLOG DEV