Python Dictionary values() Function
The Dictionary values()
method returns a list of values from a dictionary.
Syntax
my_dictionary.values()
values() Parameters
Python Dictionary values()
function does not take any parameters.
values() Return Value
Python Dictionary values()
function returns a view object that displays the list of all the values.
Examples
Example 1: Get all values of a dictionary
For example, let's print all the values of the dictionary:
my_dict = {'name': 'Tom', 'age': 25}
print(my_dict.values()) # Output: dict_values(['Tom', 25])
output
dict_values(['Tom', 25])
Example 2: Iterate through values of a dictionary using values()
The keys()
method is generally used to iterate through all the values from a dictionary.
For example, let's iterate through values of a dictionary:
my_dict = {'name': 'Tom', 'age': 25}
for x in my_dict.values():
print(x)
output
Tom
25
Example 3: values() returns a View Object (Reflecting Changes to the Dictionary)
The object returned by values()
is a view object.
It provides a dynamic view on the dictionary’s entries: this means that when the dictionary changes, the view reflects these changes.
For example, when an item is deleted from the dictionary, the view object automatically updates to reflect the change:
my_dict = {'name': 'Tom', 'age': 25}
# Assign dict values to view_obj
view_obj = my_dict.values()
# print view_obj
print(view_obj) # Output: dict_values(['Tom', 25])
# Delete a key from the dictionary
del my_dict['age']
# print view_obj to see reflected changes
print(view_obj) # Output: dict_values(['Tom'])
output
dict_values(['Tom', 25])
dict_values(['Tom'])
The same happens when an item is modified in the dictionary:
my_dict = {'name': 'Tom', 'age': 25}
# Assign dict values to view_obj
view_obj = my_dict.keys()
# print view_obj
print(view_obj) # Output: dict_values(['Tom', 25])
# modify dictionary my_dict
my_dict['job'] = 'Developer'
# view_obj reflects changes done to dictionary my_dict
print(view_obj) # Output: dict_values(['Tom', 25, 'Developer'])
output
dict_values(['Tom', 25])
dict_values(['Tom', 25, 'Developer'])