iterate
dictionary

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.

Practice algorithms

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.

python
1scores = {"alice": 91, "bob": 84, "cara": 95}
2
3for name in scores:
4    print(name, scores[name])

This is concise and common. Use this when key lookup inside loop is intentional.

Equivalent explicit form uses keys.

python
for name in scores.keys():
    print(name)

Both forms iterate in insertion order in modern Python versions.

Iterate Values Only

If key is irrelevant, iterate values directly.

python
for score in scores.values():
    print(score)

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.

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

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.

python
for idx, (name, score) in enumerate(scores.items(), start=1):
    print(idx, name, score)

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:

python
for name in sorted(scores):
    print(name, scores[name])

Sorted by value descending:

python
for name, score in sorted(scores.items(), key=lambda pair: pair[1], reverse=True):
    print(name, score)

Use sorted views only when needed because sorting adds extra cost.

Transforming Dictionaries Cleanly

Dictionary comprehensions combine iteration and transformation in one expression.

python
1prices = {"book": 12.0, "pen": 2.5, "bag": 30.0}
2
3with_tax = {item: round(amount * 1.13, 2) for item, amount in prices.items()}
4print(with_tax)

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:

python
for key in scores:
    if scores[key] < 90:
        del scores[key]

Safe pattern using a copied key list:

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

Alternative safe pattern creates a new filtered dictionary.

python
scores = {k: v for k, v in scores.items() if v >= 90}

Nested Dictionary Iteration

For structured data, nested loops keep traversal explicit.

python
1data = {
2    "team-a": {"open": 3, "closed": 7},
3    "team-b": {"open": 5, "closed": 4},
4}
5
6for team, metrics in data.items():
7    print(team)
8    for status, count in metrics.items():
9        print("  ", status, count)

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:

  • items usually 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.

python
1from typing import Dict
2
3def total(points: Dict[str, int]) -> int:
4    acc = 0
5    for _, value in points.items():
6        acc += value
7    return acc

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 values for value-only loops and items for key-value loops.
  • Use enumerate and sorted intentionally when needed.
  • Avoid mutating dictionary size during live iteration.
  • Prefer readable iteration patterns and profile only when performance is truly a concern.

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.