Skip to main content

How to Loop over a Dictionary's Keys and Values in Python with items()

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A plain for loop over a dictionary gives you only its keys. When you need each key together with its value, loop over .items(). This guide does it on Python 3.15.2, and shows the two errors people hit most.

Syntax​

Syntax
for <key>, <value> in <dictionary>.items():
...
PartWhat it means
<dictionary>.items()Every key with its value, as (key, value) pairs, in the order the keys were added
<key>, <value>The two names each pair is unpacked into, one turn of the loop at a time

The Python documentation describes items() as returning "a new view of the dictionary's items ((key, value) pairs)."

The Example​

A dictionary maps two names to ages. The script prints a sentence for each person, then prints what items() returns on its own.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

items.py
ages = {"Ada": 36, "Grace": 45}

for name, age in ages.items():
print(f"{name} is {age}")

print(ages.items())

The items.py script in a macOS-style code window: a dictionary of two names and ages, a for loop over ages.items() that prints each name is age, then a print of ages.items() itself.

Step 2: Run It​

Terminal
uv run python items.py
Output
Ada is 36
Grace is 45
dict_items([('Ada', 36), ('Grace', 45)])

The terminal after uv run python items.py: Ada is 36, Grace is 45, then dict_items([('Ada', 36), ('Grace', 45)]).

Each turn of the loop got one pair, such as ('Ada', 36), and unpacked it into name and age. The last line shows the view itself: a dict_items object holding the pairs. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Forgetting .items(): for name, age in ages:The loop gets only the keys, and Python tries to split the text "Ada" into two names: ValueError: too many values to unpack (expected 2)Loop over ages.items()
Adding or removing keys inside the loopRuntimeError: dictionary changed size during iterationLoop over a copy, list(ages.items()), or collect the changes and apply them after the loop

FAQ​

How do I get only the values?​

Use ages.values(). For only the keys, loop over the dictionary itself or use ages.keys().

Is the view a copy of the dictionary?​

No. A view follows the dictionary: if the dictionary changes after you call items(), the view shows the change.

Conclusion​

for name, age in ages.items() gave each key with its value, and printed Ada is 36 and Grace is 45.

Additional Resources​