Python Dictionary values() Method

The values() method returns a view object that displays a list of all the values in the dictionary. The view object is dynamic, meaning that any changes to the dictionary will be reflected in the view object.

Syntax

dictionary.values()

Parameters

The values() method doesn’t accept any parameters.

Return value

Returns a view object that displays a list of all the values in the dictionary.

Example:

person = {"name": "James", "age": 35, "city": "London"}

print(person.values()) # Output: dict_values(['James', 35, 'London'])

Iterating over the values of a dictionary

The view object returned by the values() method is iterable. Therefore, you can loop over it directly.

For example:

person = {"name": "James", "age": 35, "city": "New York"}

for value in person.values():
    print(value)

Output:

James
35
New York

Converting view object to list

The view object is not a list, but you can convert it to a list using the list() function if needed.

For example:

person = {"name": "James", "age": 35, "city": "New York"}

values = person.values()

# Converting to a list
values_list = list(values)
print(values_list) # Output: ['James', 35, 'New York']

View object is dynamic

The view object returned by values() method is dynamic, meaning if the dictionary is modified after the view object is created, the changes are reflected in the view object

For example:

person = {"name": "James", "age": 35}

values = person.values()

person["city"] = "Los Angeles"
print(values) # Output; dict_values(['James', 35, 'Los Angeles'])

When to use values()

Use values() method when you need to access, iterate over, or check for the existence of a specific value in a dictionary.

Example: Check for a specific value in a dictionary.

person = {"name": "James", "age": 35, "city": "Los Angeles"}

if "Los Angeles" in person.values():
    print("Los Angeles value exists!") # Output: Los Angeles value exists!