How to Iterate Over Dictionary Items in Python Easily
To iterate over dictionary items in Python, use the
items() method with a for loop like for key, value in dict.items():. This lets you access each key and its corresponding value in the dictionary.Syntax
The basic syntax to loop over dictionary items is:
dict.items(): Returns pairs of keys and values.for key, value in dict.items():: Loops through each key-value pair.
python
for key, value in my_dict.items(): # use key and value here
Example
This example shows how to print each key and value from a dictionary using items().
python
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}
for key, value in my_dict.items():
print(f"{key}: {value}")Output
apple: 3
banana: 5
orange: 2
Common Pitfalls
One common mistake is trying to loop over the dictionary directly to get keys and values together, which only gives keys.
Wrong way:
for item in my_dict:
print(item)This prints only keys, not values.
Right way:
for key, value in my_dict.items():
print(key, value)python
my_dict = {'a': 1, 'b': 2}
# Wrong way - prints only keys
for item in my_dict:
print(item)
# Right way - prints keys and values
for key, value in my_dict.items():
print(key, value)Output
a
b
a 1
b 2
Quick Reference
Remember these tips when iterating dictionary items:
- Use
dict.items()to get key-value pairs. - Unpack pairs in the loop as
for key, value in dict.items():. - Looping directly over the dictionary gives only keys.
Key Takeaways
Use
dict.items() to get both keys and values when looping.Unpack key and value in the loop like
for key, value in dict.items():.Looping directly over a dictionary only gives keys, not values.
Always use
items() when you need both parts of the dictionary.This method works for all Python versions 3.x and above.