How to Loop Through a Dictionary in Python

Short answer
Use for key, value in my_dict.items(): to loop over keys and values together. Loop over my_dict (or .keys()) for keys only and .values() for values only.

A dictionary stores pairs, so there are three things you might want to loop over: the keys, the values, or both at once. Which one you pick changes what the loop variable contains.

Python 3.7 and newer iterate in insertion order, so you get the items in the order they were added. This page covers the three loops, sorted loops, and the error you get if you change the dictionary while looping.

Quick facts
Keys and valuesfor k, v in d.items():
Keys onlyfor k in d: or d.keys()
Values onlyfor v in d.values():
OrderInsertion order (Python 3.7+)
Do notAdd or delete keys while looping over the same dictionary

Loop through keys and values together with items()

items() yields (key, value) pairs, and the for loop can unpack each pair into two names. This is the form you will use most.

Python
stock = {"pen": 40, "ink": 5, "book": 12}
for item, qty in stock.items():
    print(item, qty)

Loop through only the keys or only the values

A plain for key in d: already goes over keys, so .keys() is optional. When you do not need the keys, values() is clearer and avoids a lookup per item.

Python
stock = {"pen": 40, "ink": 5, "book": 12}
for name in stock:
    print(name)
print(sum(stock.values()))

Loop in sorted order

Wrap the dictionary or its items in sorted() to control the order. Sorting by key is the default for pairs; use key= to sort by value (more in sort a dictionary by value).

stock = {"pen": 40, "ink": 5, "book": 12}

for name in sorted(stock):
    print(name, stock[name])

for name, qty in sorted(stock.items(), key=lambda kv: kv[1]):
    print(name, qty)

Do not change the dictionary size while looping

Adding or removing keys during a loop raises RuntimeError: dictionary changed size during iteration. Loop over a copy of the keys, list(d), or build a new dictionary. Changing the value of an existing key is safe.

Which dictionary loop should you use?

You needLoopLoop variable holds
Keys and valuesfor k, v in d.items()A key and its value
Only keysfor k in dEach key
Only valuesfor v in d.values()Each value
Position as wellfor i, (k, v) in enumerate(d.items())Index, key, value
Sorted keysfor k in sorted(d)Each key, alphabetical

Examples you can run

Press Run, then edit the code and run it again.

Print every key and value

Unpack each pair into two names.

Print every key and value
scores = {"Asha": 82, "Ben": 91, "Chen": 75}
for name, score in scores.items():
    print(f"{name}: {score}")
Expected outputAsha: 82
Ben: 91
Chen: 75

Total all values

When you only need the numbers, loop over values().

Total all values
cart = {"pen": 2, "book": 15, "ink": 4}
total = 0
for price in cart.values():
    total += price
print(total)
Expected output21

Number the entries with enumerate()

Wrap items() in enumerate() and unpack with parentheses.

Number the entries with enumerate()
scores = {"Asha": 82, "Ben": 91}
for i, (name, score) in enumerate(scores.items(), start=1):
    print(i, name, score)
Expected output1 Asha 82
2 Ben 91

Safely remove keys while looping

Iterate over a copy of the keys so the dictionary can change.

Safely remove keys while looping
stock = {"pen": 40, "ink": 0, "book": 12, "glue": 0}
for name in list(stock):
    if stock[name] == 0:
        del stock[name]
print(stock)
Expected output{'pen': 40, 'book': 12}

Common mistakes

Unpacking a dictionary directly

✗ Wrong

scores = {"Asha": 82}
for name, score in scores:
    print(name, score)
ValueError: too many values to unpack (expected 2)

✓ Right

scores = {"Asha": 82}
for name, score in scores.items():
    print(name, score)

Looping over a dictionary gives only keys. Call .items() to get pairs.

Deleting keys during the loop

✗ Wrong

d = {"a": 0, "b": 1}
for k in d:
    if d[k] == 0:
        del d[k]
RuntimeError: dictionary changed size during iteration

✓ Right

d = {"a": 0, "b": 1}
d = {k: v for k, v in d.items() if v != 0}

Loop over list(d) or build a new dictionary with a comprehension.

Expecting the value from a plain loop

✗ Wrong

prices = {"pen": 2}
for p in prices:
    print(p + 1)
TypeError: can only concatenate str (not "int") to str

✓ Right

prices = {"pen": 2}
for p in prices.values():
    print(p + 1)

p is the key. Use prices.values() or prices[p] to reach the value.

How to Loop Through a Dictionary in Python: questions people ask

How do I loop through a dictionary in Python?

Use for key, value in my_dict.items():. It gives you each key together with its value on every iteration.

Is a Python dictionary ordered when I loop over it?

Yes. Since Python 3.7 dictionaries iterate in the order the keys were first inserted.

How do I loop through a dictionary in sorted order?

Use for key in sorted(my_dict): for key order, or sorted(my_dict.items(), key=lambda kv: kv[1]) for value order.

Keep learning

Step-by-step lessons:
Python DictionariesPython for LoopsPython Dictionary Methods

Related:
Python Dictionary items() MethodPython Dictionary keys() MethodPython Dictionary values() MethodHow to Sort a Dictionary by Value in PythonPython enumerate() Function

More in lists, dicts and sets:
How to Remove Duplicates from a List in PythonHow to Sort a Dictionary by Value in PythonHow to Merge Two Dictionaries in PythonHow to Reverse a List in PythonHow to Flatten a List of Lists in PythonHow to Check if a List Is Empty in PythonHow to Get the Last Element of a List in PythonHow to Count Occurrences in a List in Python See all →