Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Dictionary Value Iteration Explained

Learn how to iterate over dictionary values in Python with .values(), .items(), and comprehensions, including performance tradeoffs and safe modification.

~4 min readPython
#dictionary iteration#Python loops#values() method#items() method
Illustration of iterating over dictionary values in Python, showing a loop over a dict with key-value pairs.

When you need to process the values stored in a Python dictionary, the way you iterate affects readability, memory use, and whether you can modify the dictionary safely. The right approach depends on whether you need the keys, the values, or both, and on whether you plan to change the dictionary while looping.

Using .values() for Direct Value Iteration

The simplest way to iterate over just the values is the values() method. It returns a view object that reflects the current dictionary contents. Use this form when keys are irrelevant.

python
scores = {"alice": 92, "bob": 85, "carol": 88} for score in scores.values(): print(score)

This loop prints each score without exposing the keys. The view object is dynamic: it stays synchronized with the dictionary, including in-place value changes. Adding or removing keys during iteration raises a RuntimeError. The view also supports membership tests and iteration without copying the values, so it is memory-efficient.

Iterating Over Keys and Values with .items()

When you need both the key and its associated value, items() is the standard choice. It returns a view of key-value tuples, which you can unpack directly in the loop.

python
for name, score in scores.items(): print(f"{name}: {score}")

This is the most readable way to access both pieces of information. It avoids a separate key lookup, which would be necessary if you iterated over the keys and then accessed the dictionary. Using items() is also faster than iterating over keys() and then indexing, because it avoids the extra lookup.

When to Iterate Over the Dictionary Directly

Iterating over a dictionary directly yields its keys. This is useful when you only need keys, but if you also need values, you must perform a lookup. For small dictionaries, the performance difference is negligible, but for large ones, the extra lookup adds overhead. Prefer direct iteration when you only need keys, and use items() when you need values as well.

python
for key in scores: print(key) # only keys

This pattern is common when checking for the existence of a key or when the value is not needed for the current operation.

Building Lists and Comprehensions from Values

Comprehensions allow you to transform values concisely. For example, to create a list of doubled scores:

python
doubled = [score * 2 for score in scores.values()]

If you need to filter and transform, you can combine conditions:

python
passed = {name: score for name, score in scores.items() if score >= 60}

This creates a new dictionary containing only items that meet the condition. Comprehensions are more readable than an explicit loop with append() and are generally preferred in Python when the logic fits on one line.

Performance and Memory Considerations

The values() and items() methods return view objects, not copies. This means iterating over them does not allocate a new list or dictionary, which is beneficial for memory usage when working with large dictionaries. In contrast, using list(scores.values()) creates a new list, which can be expensive if you only need to iterate once.

Iteration order follows insertion order in Python 3.7 and later. Before Python 3.7, insertion order was not guaranteed by the language. The view objects are iterable multiple times, but they reflect the current state of the dictionary, so changes after the view is created are visible.

When you need to iterate and modify the dictionary, you must be careful. Adding or removing items during iteration raises a RuntimeError because the dictionary size changes. A common workaround is to iterate over a copy of the keys:

python
for key in list(scores.keys()): if scores[key] < 60: del scores[key]

This creates a list of keys first, so the iteration is safe. If you need to remove items based on their values, use list(scores.items()) so you have both the key and value in the snapshot.

Handling Missing Keys and Edge Cases

Missing keys can be a concern if you are using a separate key list or if the dictionary is mutated by another part of the code. Using get() with a default value can prevent KeyError:

python
for key in required_keys: value = scores.get(key, 0) print(value)

When iterating over values() or items(), you are guaranteed to see only existing entries, so missing keys are not an issue. Edge cases arise when the dictionary contains None values or when you need to distinguish between a missing key and a key with a None value. In such cases, get() with a sentinel is useful.

Choosing the Right Iteration Method for Your Use Case

The decision among values(), items(), and direct iteration depends on what you need:

  • Use values() when keys are irrelevant and you only need to process the stored data.
  • Use items() when you need both keys and values, especially for building new dictionaries or when the key is required for the logic.
  • Use direct iteration when you only need keys, or when you want to explicitly look up values for a subset of keys.

For large dictionaries, prefer view-based iteration to avoid copying. For comprehensions, choose the method that produces the desired output type. If you need to modify the dictionary during iteration, iterate over a snapshot, such as list(scores.items()), to avoid runtime errors. These choices keep your code efficient and maintainable.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.