Python Dictionary values()

Python dictionary values() method

Python dictionary values() method returns a set-like object that can provide a view on the dictionary’s values.

In this tutorial, you will learn about dictionary values() method in Python, and its usage, with the help of example programs.

Syntax of dict values()

The syntax of dictionary values() method is

dictionary.values()

Parameters

The dictionary values() method takes no parameters.

Return value

The dictionary values() method returns an object of type dict_values.

Examples for values() method

1. Getting the values of given dictionary in Python

In this example, we are given a dictionary in my_dict with some initial key:value pairs. We have to get only the values in this dictionary.

We shall call values() method on the given dictionary object my_dict, and print the returned value to standard output.

Python Program

my_dict = {
    'foo':12,
    'bar':14
}

print(my_dict.values())
Run Code Copy

Output

dict_values([12, 14])

You may convert the dict_values object to a list using list() built-in function.

In the following program, we have converted the dict_values object to a list values, and then printed this list of values to output.

Python Program

my_dict = {
    'foo':12,
    'bar':14
}

values = list(my_dict.values())
print(values)
Run Code Copy

Output

[12, 14]

2. Iterate over values of dictionary using values() method in Python

In this example, we will use dictionary values() method to iterate over the values of the dictionary in a For loop.

Python Program

my_dict = {
    'foo':12,
    'bar':14
}

for value in my_dict.values():
    print(value)
Run Code Copy

Output

12
14

Summary

In this tutorial of Python Dictionary Methods, we learned how to use Dictionary values() method to get only the values in a dictionary, with help of well detailed Python programs.

Code copied to clipboard successfully 👍