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.
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.
For values only:
For both key and value (most common):
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.
Dictionary comprehensions can filter/transform while iterating:
For index-aware loops:
3. Safe mutation strategies during iteration
Do not change dictionary size while iterating over its live view. That raises runtime errors.
Unsafe:
Safe alternatives:
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()orkeys()live views. - Relying on implicit order when business logic requires deterministic sorted output.
- Using repeated
dict[key]lookups whenitems()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
- Is there a way to measure how sorted a list is?
- Is there a way to pretty print Swift dictionaries to the console?
- Is there a way to pretty print Swift dictionaries to the console?
- Is there a way to sort a list in python until the first sorted k elements are found?
- Is there a way to make this Python kNN function more efficient?
- Is there a way to perform if in python's lambda?
- Is there a way to store gzip's dictionary from a file?
- Is there a way to use decision trees with categorical variables without one-hot encoding?

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 courseTrack 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.