Python
programming
dictionaries
for loops
coding tips

Iterating over dictionaries using 'for' loops

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 once you know what view you need: keys, values, or key-value pairs. Most confusion comes from using the wrong dictionary method for the job or from mutating the dictionary while looping over it.

The Default Loop Iterates Over Keys

When you loop over a dictionary directly, Python gives you the keys.

python
1person = {
2    "name": "Ava",
3    "age": 30,
4    "city": "Toronto",
5}
6
7for key in person:
8    print(key)

This is exactly the same as:

python
for key in person.keys():
    print(key)

Use this when you only need the keys or when you will look up values manually.

Loop Over Values With .values()

If only the values matter, use .values().

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

This is clearer than looping over keys and then indexing back into the dictionary for each value.

Loop Over Both With .items()

If you need both the key and the value, .items() is usually the best choice.

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

This is the idiomatic pattern in Python and the one you will use most often in application code.

When Order Matters

Modern Python dictionaries preserve insertion order. That means iteration follows the order in which keys were added.

python
1data = {"b": 2, "a": 1, "c": 3}
2
3for key, value in data.items():
4    print(key, value)

If you want alphabetical order or some other ordering rule, say so explicitly.

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

Do not rely on insertion order if the real requirement is sorted order.

Enumerating Dictionary Iteration

If you need a loop counter as well, wrap the dictionary view in enumerate.

python
for index, (key, value) in enumerate(person.items(), start=1):
    print(index, key, value)

This is useful for numbered reports or formatted output.

Filtering During Iteration

You can add conditions in the loop body just like any other for loop.

python
1scores = {"math": 95, "history": 78, "science": 88}
2
3for subject, score in scores.items():
4    if score >= 80:
5        print(subject, score)

This is often clearer than creating a temporary filtered dictionary unless you actually need that filtered structure later.

Do Not Mutate While Iterating

A common bug is changing the size of the dictionary during iteration.

python
1prices = {"apple": 1, "banana": 2, "pear": 3}
2
3for key in list(prices.keys()):
4    if prices[key] < 2:
5        del prices[key]
6
7print(prices)

The important part is list(prices.keys()). That creates a snapshot so the loop is not invalidated by deletions.

If you mutate the dictionary directly while iterating over the live view, Python can raise a runtime error.

Nested Dictionaries

When values are dictionaries themselves, you can unpack step by step.

python
1users = {
2    "u1": {"name": "Ava", "role": "admin"},
3    "u2": {"name": "Noah", "role": "editor"},
4}
5
6for user_id, info in users.items():
7    print(user_id, info["name"], info["role"])

This pattern is common in JSON-like application data.

Common Pitfalls

The most common mistake is looping over a dictionary directly and forgetting that the loop variable is the key, not the value.

Another mistake is using .keys() and then repeatedly indexing into the dictionary when .items() would be clearer and simpler.

Developers also get into trouble by mutating the dictionary during iteration. If keys may be added or removed, iterate over a copied list of keys instead.

Finally, do not confuse insertion order with sorted order. If sorted output matters, call sorted explicitly.

Summary

  • Looping over a dictionary directly gives you keys.
  • Use .values() when only values matter.
  • Use .items() when you need both keys and values.
  • Use enumerate or sorted when numbering or ordering is required.
  • Avoid changing the dictionary's size while iterating over its live views.

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.