W3docs

Loop Dictionaries

Learn every way to loop through a Python dictionary: keys, values, items, filtered loops, comprehensions, and safe in-loop modifications with examples.

Python dictionaries store data as key-value pairs, and you will regularly need to walk through them — to print every entry, filter data, transform values, or build new structures. This chapter covers every standard technique for iterating over a dictionary, explains which method to reach for in each situation, and highlights the most common mistake: modifying a dictionary while you are looping through it.

If you are new to dictionaries, read Python Dictionaries first. For general loop syntax, see Python For Loops.

Looping Over Keys

When you use a bare for loop on a dictionary, Python iterates over its keys by default.

Loop over dictionary keys

person = {"name": "Alice", "age": 30, "city": "Berlin"}

for key in person:
    print(key)

Output:

name
age
city

Calling .keys() is equivalent and makes the intent more explicit:

python— editable, runs on the server

Once you have the key, you can look up its value inside the loop:

person = {"name": "Alice", "age": 30, "city": "Berlin"}

for key in person:
    print(key, "->", person[key])

Output:

name -> Alice
age -> 30
city -> Berlin

When to use .keys()

Use the bare for key in d form when you only need keys. Use d.keys() explicitly when you want to test membership ("name" in d.keys()) or pass the view to another function. For a simple membership test, though, if "name" in d is faster.

Looping Over Values

Use .values() when you only need the values and do not care about the keys.

Loop over dictionary values

scores = {"math": 92, "science": 87, "english": 95}

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

Output:

92
87
95

A common use case is computing a summary across all values:

scores = {"math": 92, "science": 87, "english": 95}

total = sum(scores.values())
average = total / len(scores)
print(f"Average score: {average:.1f}")

Output:

Average score: 91.3

Looping Over Key-Value Pairs with .items()

.items() returns each entry as a (key, value) tuple. You can unpack the tuple directly into two variables. This is the most versatile iteration method and the one you will reach for most often.

Loop over key-value pairs

person = {"name": "Alice", "age": 30, "city": "Berlin"}

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

Output:

name: Alice
age: 30
city: Berlin

Filtering While Looping

Combine a for loop with an if condition to process only the entries you care about.

Print only in-stock items

inventory = {"apples": 5, "bananas": 0, "oranges": 3, "grapes": 0}

print("In stock:")
for item, qty in inventory.items():
    if qty > 0:
        print(f"  {item}: {qty}")

Output:

In stock:
  apples: 5
  oranges: 3

Sorting Dictionary Entries

Python 3.7+ guarantees that dictionaries keep insertion order. If you need a different order, sort the keys or items before looping — the dictionary itself is not affected.

Sort by key (alphabetical)

book = {"banana": 7, "apple": 3, "cherry": 12}

for fruit in sorted(book):
    print(f"{fruit}: {book[fruit]}")

Output:

apple: 3
banana: 7
cherry: 12

Sort by value

Pass a key function to sorted() to control the sort criterion.

book = {"banana": 7, "apple": 3, "cherry": 12}

for fruit, count in sorted(book.items(), key=lambda item: item[1], reverse=True):
    print(f"{fruit}: {count}")

Output:

cherry: 12
banana: 7
apple: 3

Using enumerate() While Looping

Wrap .items() in enumerate() to get a running index alongside each key-value pair.

colors = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}

for index, (name, hex_code) in enumerate(colors.items()):
    print(f"{index}: {name} -> {hex_code}")

Output:

0: red -> #FF0000
1: green -> #00FF00
2: blue -> #0000FF

Dictionary Comprehensions

A dictionary comprehension builds a new dictionary from an existing one in a single expression. The syntax mirrors list comprehensions but uses curly braces and a colon between key and value.

Apply a 10% discount to every price

prices = {"apple": 1.20, "banana": 0.50, "orange": 0.80}

discounted = {item: round(price * 0.9, 2) for item, price in prices.items()}
print(discounted)

Output:

{'apple': 1.08, 'banana': 0.45, 'orange': 0.72}

You can add a filter condition at the end:

Keep only students who scored 90 or above

students = {
    "Alice": {"grade": "A", "score": 95},
    "Bob":   {"grade": "B", "score": 82},
    "Carol": {"grade": "A", "score": 91},
}

top_students = {name: info for name, info in students.items() if info["score"] >= 90}
print(top_students)

Output:

{'Alice': {'grade': 'A', 'score': 95}, 'Carol': {'grade': 'A', 'score': 91}}

Looping Over Nested Dictionaries

When values are themselves dictionaries (see Nested Dictionaries), access the inner entries with a second subscript or a second loop.

Print all fields for each student

students = {
    "Alice": {"grade": "A", "score": 95},
    "Bob":   {"grade": "B", "score": 82},
    "Carol": {"grade": "A", "score": 91},
}

for name, info in students.items():
    print(f"{name}: grade={info['grade']}, score={info['score']}")

Output:

Alice: grade=A, score=95
Bob: grade=B, score=82
Carol: grade=A, score=91

Modifying a Dictionary While Looping — the Key Gotcha

You cannot add or remove keys from a dictionary while you are iterating over it. Python raises a RuntimeError immediately:

d = {"a": 1, "b": 2, "c": 3}

# This raises RuntimeError: dictionary changed size during iteration
for key in d:
    if d[key] == 2:
        del d[key]

The safe pattern is to collect the keys you want to remove first, then delete them after the loop:

Safe deletion after looping

config = {"debug": True, "verbose": True, "timeout": 30}

keys_to_remove = [k for k, v in config.items() if v is True]
for k in keys_to_remove:
    del config[k]

print(config)

Output:

{'timeout': 30}

The same principle applies to adding keys: collect the new pairs, then update the dictionary with update() or direct assignment after the loop.

Choosing the Right Method

GoalMethod
Iterate over keys onlyfor key in d or for key in d.keys()
Iterate over values onlyfor value in d.values()
Iterate over bothfor key, value in d.items()
Build a new dictionaryDictionary comprehension
Sort entriessorted(d) or sorted(d.items(), key=...)
Index + key-valueenumerate(d.items())

For the full set of dictionary operations, see Python Dictionary Methods and Copy Dictionaries.

Practice

Practice
Which of the following ways can be used to loop through a dictionary in Python, as learned from the webpage at W3docs?
Which of the following ways can be used to loop through a dictionary in Python, as learned from the webpage at W3docs?
Was this page helpful?