dict.values() method in Python returns a view object that contains all the values of the dictionary. This object updates automatically when the dictionary changes and is useful when only values are needed.
Example: In this example, values() is used to get all values from a dictionary.
d = {'A': 'Python', 'B': 'Java', 'C': 'C++'}
print(d.values())
Output
dict_values(['Python', 'Java', 'C++'])
Explanation: d.values() returns a view object containing all values of dictionary d.
Syntax
dict_name.values()
- Parameters: No parameters are required.
- Returns: Returns a dynamic view object containing all dictionary values.
Examples
Example 1: Here, the code retrieves all dictionary values and prints them using a loop. This helps access each value individually.
d = {'x': 10, 'y': 20, 'z': 30}
for v in d.values():
print(v)
Output
10 20 30
Explanation: d.values() returns all values and for v in d.values() accesses each value one by one.
Example 2: In this example, the values view object is converted into a list. This allows indexing and other list operations.
d = {'a': 1, 'b': 2, 'c': 3}
v = list(d.values())
print(v)
Output
[1, 2, 3]
Explanation: list(d.values()) converts the view object into a list.
Example 3: Here, the code checks whether a specific value exists in the dictionary.
d = {'p': 100, 'q': 200}
print(200 in d.values())
Output
True
Explanation: d.values() provides all values and 200 in d.values() checks if value exists.