How 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
Iterating over a Python dictionary is simple, but the best pattern depends on whether you need keys, values, pairs, sorted order, or safe mutation behavior. Small iterator choices can affect readability and performance in larger loops. A clear mental model of keys, values, and items helps you avoid subtle bugs.
Basic Iteration Returns Keys
Looping directly over a dictionary yields keys.
This is concise and common. Use this when key lookup inside loop is intentional.
Equivalent explicit form uses keys.
Both forms iterate in insertion order in modern Python versions.
Iterate Values Only
If key is irrelevant, iterate values directly.
This avoids unnecessary dictionary lookups and communicates intent clearly.
Iterate Key-Value Pairs with items
Most practical loops need both key and value. Use items for this.
This is usually cleaner than looping keys then indexing dictionary each time.
Add Index While Iterating
If you need position plus key-value pair, combine enumerate with items.
This is useful for numbered reports and deterministic display output.
Sorted Iteration Patterns
Dictionaries preserve insertion order, but sometimes you need deterministic sorted order by key or value.
Sorted by key:
Sorted by value descending:
Use sorted views only when needed because sorting adds extra cost.
Transforming Dictionaries Cleanly
Dictionary comprehensions combine iteration and transformation in one expression.
For complex transformations, prefer explicit loop for readability.
Safe Mutation While Iterating
Do not add or delete keys directly while iterating over the live dictionary view. That can raise runtime errors.
Unsafe pattern:
Safe pattern using a copied key list:
Alternative safe pattern creates a new filtered dictionary.
Nested Dictionary Iteration
For structured data, nested loops keep traversal explicit.
When depth grows, helper functions often improve maintainability.
Performance Notes
In most business code, readability matters more than micro-optimization. Still, some practical guidance helps:
itemsusually avoids repeated lookups.- sorting inside hot loops can dominate runtime.
- converting views to list creates copy overhead.
If performance is critical, profile first with realistic input sizes.
Iteration in Typed and Data Pipeline Code
In typed codebases, iterating over dictionaries with known key and value types improves static checks.
Clear type hints reduce iteration mistakes in larger systems.
Common Pitfalls
A common pitfall is modifying dictionary size during direct iteration, which can raise errors or produce unpredictable behavior. Another is using key loops when items would be clearer and faster for pair access. Teams also often assume sorted output without explicitly sorting, then encounter unstable report ordering after refactors. Finally, overusing one-line comprehensions for complex logic can hurt readability and maintainability.
Summary
- Direct dictionary iteration yields keys.
- Use
valuesfor value-only loops anditemsfor key-value loops. - Use
enumerateandsortedintentionally when needed. - Avoid mutating dictionary size during live iteration.
- Prefer readable iteration patterns and profile only when performance is truly a concern.
Related reading
- Loop (for each) over an array in JavaScript
- Sort array of objects by string property value
- What and where are the stack and heap?
- A-star algorithm
- A Algorithm for very large graphs, any thoughts on caching shortcuts?
- A column-vector y was passed when a 1d array was expected
- A difference in style IDictionary vs Dictionary
- A divide-and-conquer algorithm for counting dominating points?

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.