How to Loop through Dictionary Values in Python?
Python Dictionary - Loop through Values
A dictionary is a collection of key:value pairs. At times, it is required to loop through only the values in a Dictionary.
You can access the values alone of a Python Dictionary using dict.values() on dictionary variable. Then use Python For Loop to iterate through those values.
Examples
1. Loop through values in given dictionary using values()
In this example, we will initialize a dictionary with some key:value pairs, and use for loop to iterate through values in the dictionary.
Python Program
myDictionary = {
"name": "Lini",
"year": 1989,
"expertise": "data analytics"}
#iterate through dictionary
for value in myDictionary.values():
print(value)Explanation
- A dictionary
myDictionaryis created with three key-value pairs:"name": "Lini","year": 1989, and"expertise": "data analytics". - The
values()method is called onmyDictionary, which returns a view object containing all the values of the dictionary. - A
forloop is used to iterate over the values in the dictionary, wherevaluerepresents the current value in each iteration. - The
print()function is used to display each value. The output will be: Lini1989data analytics
Output
Lini
1989
data analytics2. Loop through values in given dictionary using items()
Similar to Dictionary.values(), the function Dictionary.items() returns key,value during each iteration. You can access values from the key:value, while traversing through the dictionary.
Python Program
myDictionary = {
"name": "Lini",
"year": 1989,
"expertise": "data analytics"}
#iterate through dictionary
for key,value in myDictionary.items():
print(value)Explanation
- A dictionary
myDictionaryis created with three key-value pairs:"name": "Lini","year": 1989, and"expertise": "data analytics". - The
items()method is called onmyDictionary, which returns a view object containing the key-value pairs as tuples. - A
forloop is used to iterate through each key-value pair, wherekeyandvaluerepresent the current key and corresponding value in each iteration. - The
print()function is used to display only the values, which are: Lini1989data analytics
Output
Lini
1989
data analyticsSummary
In this tutorial of Python Examples, we learned how to iterate through values of a Dictionary with the help of well detailed examples.