How to Iterate Over Dictionary Values in Python Easily
To iterate over dictionary values in Python, use the
values() method with a for loop like for value in my_dict.values():. This lets you access each value directly without the keys.Syntax
Use the values() method on a dictionary to get all its values. Then loop through them with a for loop.
my_dict.values(): Returns a view of all values in the dictionary.for value in ...:: Loops over each value one by one.
python
for value in my_dict.values(): print(value)
Example
This example shows how to print all values from a dictionary of fruits and their colors.
python
my_dict = {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'}
for value in my_dict.values():
print(value)Output
red
yellow
purple
Common Pitfalls
One common mistake is trying to loop directly over the dictionary, which gives keys, not values. Another is using items() when only values are needed, which adds unnecessary complexity.
Wrong way (loops keys):
for value in my_dict:
print(value) # prints keys, not valuesRight way (loops values):
for value in my_dict.values():
print(value)Quick Reference
Remember these tips when iterating dictionary values:
- Use
dict.values()to get values only. - Use
for value in dict.values():to loop values. - Looping directly over dict loops keys, not values.
Key Takeaways
Use
dict.values() to access dictionary values directly.Loop with
for value in dict.values(): to iterate values.Looping directly over a dictionary gives keys, not values.
Avoid using
items() if you only need values.This method works for all Python versions and is simple to read.