Python dictionary values() Method



The Python dictionary values() method is used to retrieve the list of all the values in the dictionary.

In Python, a dictionary is a set of key-value pairs. These are also referred to as "mappings" since they "map" or "associate" the value objects with the key objects. A list of all the values related to the Python dictionary is contained in the view object that the values() method returns.

Syntax

Following is the syntax of Python dictionary values() method −

dict.values()

Parameters

This method does not accept any parameter.

Return Value

This method returns a list of all the values available in a given dictionary.

Example

The following example shows the usage of Python dictionary values() method. First we create a dictionary 'dict' which contains values: 'Zara' and '7'. Then we retrieve all the values of the dictionary using values() method.

# creating the dictionary
dict = {'Name': 'Zara', 'Age': 7}
# Printing the result
print ("Value : %s" %  dict.values())

When we run above program, it produces following result −

Value : dict_values(['Zara', 7])

Example

When an item is added in the dictionary, the view object also gets updated.

In the following example a dictionary 'dict1' is created. This dictionary contains the values: 'Lion' and 'Carnivora'. Thereafter, we append an item in the dictionary which consist of the key 'Kingdom' and its corresponding value 'Animalia'.Then all the values of the dictionary is retrieved using the values() method:

# creating the dictionary
dict_1 = {'Animal': 'Lion', 'Order': 'Carnivora'}
res = dict_1.values()
# Appending an item in the dictionary
dict_1['Kingdom'] = 'Animalia'
# Printing the result
print ("The values of the dictionary are: ", res)

While executing the above code we get the following output −

The values of the dictionary are:  dict_values(['Lion', 'Carnivora', 'Animalia'])

Example

The values() method does not raise any error if an empty dictionary is called on this method. It returns an empty dictionary.

# Creating an empty dictionary  
Animal = {} 
# Invoking the method  
res = Animal.values()  
# Printing the result  
print('The dictionary is: ', res) 

Following is an output of the above code −

The dictionary is:  dict_values([])

Example

In the following example we are iterating through the values of the dictionary using a for loop. Then the result is returned:

# Creating a dictionary
dict_1 = {'Animal': 'Lion', 'Order': 'Carnivora', 'Kingdom':'Animalia'}
# Iterating through the values of the dictionary
for res in dict_1.values():
    print(res)

Output of the above code is as follows −

Lion
Carnivora
Animalia
python_dictionary.htm
Advertisements