5 Effective Ways to Loop Through Dictionary Values in Python
You can iterate over the values in a dictionary using a loop. Here are five examples:
- Using a for loop:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for value in my_dict.values():
print(value)
Output:
1
2
3
- Using list comprehension to collect values into a list:
my_dict = {'a': 1, 'b': 2, 'c': 3}
values = [value for value in my_dict.values()]
print(values)
Output:
[1, 2, 3]
- Using a while loop:
my_dict = {'a': 1, 'b': 2, 'c': 3}
values_iterator = iter(my_dict.values())
while True:
try:
value = next(values_iterator)
print(value)
except StopIteration:
break
Output:
1
2
3
- Using map function:
my_dict = {'a': 1, 'b': 2, 'c': 3}
values = list(map(lambda x: x, my_dict.values()))
print(values)
Output:
[1, 2, 3]
- Using a generator expression:
my_dict = {'a': 1, 'b': 2, 'c': 3}
value_generator = (value for value in my_dict.values())
for value in value_generator:
print(value)
Output:
1
2
3
These examples demonstrate different ways to iterate over the values in a dictionary in Python.