Python - Print Dictionary Values
Python - Print dictionary values
To print the values in a Python Dictionary,
- Given a dictionary object my_dict.
- Call values() method on the given dictionary object. The values() method returns an iterator over the values.
- Now, you can convert this values iterator into a list and print the list of values, or use a For loop to iterate over the values iterator object and print each of the value individually.
- If you choose to print the values as a list, pass the values iterator object as argument to the list() built-in function, and print the returned list to output. The task is completed.
- Or, if you choose to print the values individually, write a For loop with the values iterator object. We iterate through the values in the dictionary.
- For each value inside the loop, print the value. The task is completed.
Examples
1. Printing the values in given dictionary as a list in Python
We are given a Python dictionary in my_dict. We have to print the values of this dictionary.
We shall get the iterator to values in the dictionary using my_dict.values(), and pass the values iterator as argument to the list(). We will get the values in the dictionary as a list. Then we shall print this list of values to output using print() function.
Python Program
my_dict = {
'apple': 10,
'banana': 20,
'cherry':30
}
values = list(my_dict.values())
print(values)
Output
[10, 20, 30]
2. Printing values in the dictionary to output one by one using For loop
We are given a Python dictionary in my_dict. We have to print the values of this dictionary one by one using a For loop.
We shall get the iterator for the values in the dictionary using my_dict.values(), and use this values iterator object in a For loop. Inside the For loop, we shall print each value to the output using print().
Python Program
my_dict = {
'apple': 10,
'banana': 20,
'cherry':30
}
for value in my_dict.values():
print(value)
Output
10
20
30
Summary
In this tutorial of Python Examples, we learned how to print the dictionary values as a list or one by one, with the help of well detailed examples.