Python dictionary values()
values() method in Python is used to obtain a view object that contains all the values in a dictionary. This view object is dynamic, meaning it updates automatically if the dictionary is modified. If we use the type() method on the return value, we get "dict_values object". It must be cast to obtain the actual list. Example:
d = {'A': 'Python', 'B': 'Java', 'C': 'C++'}
v = d.values()
print(v)
Output
dict_values(['Python', 'Java', 'C++'])
Explanation: values() method returns a dict_values view object containing all the values present in the dictionary d.
values() syntax
dict.values()
Here, dict is the dictionary from which the values are to be retrieved.
Parameters:
- values() method does not take any parameters.
Returns: This method returns a dict_values view object, which behaves like a dynamic list of all the values in the dictionary. If the dictionary is updated, the view reflects these changes automatically.
Examples of values()
Example 1: Iterating over dictionary values
This code demonstrates how to iterate over the values of a dictionary using values().
d = {'A': 'Python', 'B': 'Java', 'C': 'C++'}
for value in d.values():
print(value)
Output
Python Java C++
Explanation: values() method returns a view object that contains all the values in the dictionary. The for loop then iterates through each value and prints it.
Example 2: Dynamic nature of values()
This code shows how the values() method reflects changes made to the dictionary dynamically.
d = {'A': 'Python', 'B': 'Java'}
values = d.values()
d['C'] = 'C++'
print(values)
Output
dict_values(['Python', 'Java', 'C++'])
Explanation: When a new key-value pair is added to the dictionary, the values() view object updates automatically to include the new value 'C++'.
Example 3: Converting values() to a list
This code demonstrates how to convert dictionary values to a list.
d = {'A': 'Python', 'B': 'Java', 'C': 'C++'}
values_list = list(d.values())
print(values_list)
Output
['Python', 'Java', 'C++']
Explanation: values() method returns a view of the dictionary’s values, and using list() converts this view into an actual list object containing the values.
Related Articles: