Python
Dictionary Iteration
Code Examples
Programming
Data Structures

Is there a way to iterate over a dictionary?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Yes, Python dictionaries are fully iterable, and there are several standard patterns depending on whether you need keys, values, or key-value pairs. Choosing the right pattern improves readability and prevents errors when dictionaries are modified during iteration.

Although iteration looks simple, production code often needs additional concerns: deterministic ordering, safe mutation strategy, and performance on large mappings. This guide covers idiomatic patterns with practical examples.

Core Sections

1. Iterate keys, values, and items

By default, iterating a dictionary yields keys.

python
1data = {"cpu": 42, "mem": 73, "disk": 88}
2
3for key in data:
4    print(key)

For values only:

python
for value in data.values():
    print(value)

For both key and value (most common):

python
for key, value in data.items():
    print(f"{key} -> {value}")

items() is typically the clearest when logic uses both components.

2. Deterministic order and transformed iteration

Python 3.7+ preserves insertion order for dictionaries, but if you need sorted traversal, sort explicitly.

python
for key in sorted(data):
    print(key, data[key])

Dictionary comprehensions can filter/transform while iterating:

python
high = {k: v for k, v in data.items() if v >= 70}
print(high)

For index-aware loops:

python
for i, (k, v) in enumerate(data.items(), start=1):
    print(i, k, v)

3. Safe mutation strategies during iteration

Do not change dictionary size while iterating over its live view. That raises runtime errors.

Unsafe:

python
for k, v in data.items():
    if v < 50:
        del data[k]  # RuntimeError likely

Safe alternatives:

python
1# iterate over a snapshot
2for k, v in list(data.items()):
3    if v < 50:
4        del data[k]
5
6# or build new dict
7data = {k: v for k, v in data.items() if v >= 50}

For large dictionaries, rebuilding can be cleaner and often easier to test than in-place mutation.

Common Pitfalls

  • Assuming default iteration yields values when it actually yields keys.
  • Mutating dictionary size during iteration over items() or keys() live views.
  • Relying on implicit order when business logic requires deterministic sorted output.
  • Using repeated dict[key] lookups when items() already provides value efficiently.
  • Overcomplicating simple loops with unnecessary lambda/map constructs.

Summary

You can iterate dictionaries in Python through keys, values, or key-value pairs, with items() being the most versatile pattern. Use explicit sorting when order matters and avoid in-loop structural mutation unless iterating over a snapshot. These small practices keep dictionary iteration safe, readable, and efficient.

In performance-sensitive paths, profile iteration patterns rather than assuming one style is always faster. Readability usually matters more than micro-optimizations, but for very large dictionaries, avoiding unnecessary intermediate lists can reduce memory churn significantly. Prefer direct view iteration (items(), keys(), values()) unless you specifically need a snapshot for mutation safety.

For APIs that expose dictionary-like objects, document whether iteration order is guaranteed and whether views are live. Consumers often build assumptions around iteration behavior; making those guarantees explicit reduces integration bugs. If order is part of business logic, encode it intentionally with sorted traversal or ordered structures instead of relying on incidental insertion order.

Finally, pair iteration logic with clear typing when possible. Type hints like dict[str, int] and explicit variable naming (for metric_name, metric_value in metrics.items()) improve code clarity and reduce mistakes in larger teams.

Establishing consistent iteration conventions in a codebase reduces review friction and prevents recurring mutation-related bugs.

When dictionaries represent external payloads, validate keys before iteration and handle missing fields gracefully. Defensive iteration patterns help prevent hard failures when upstream schemas evolve unexpectedly. This is especially important in ETL and webhook handlers where partial records are common.

Prefer clarity over cleverness in iteration-heavy code.

Simple patterns are usually the most maintainable.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.