Python Dictionary values() Method

Definition

The dict.values() method returns an iterable dictionary view object of all the values in a dictionary.

Syntax

dict.values()

Parameters

  • The dict.values() method does not take any parameters.

Return-Value

  • The dict.values() method returns an iterable dictionary view object of all the values in a dictionary.

Error

The dict.values() method does not take any parameters, so no error will be returned due to the wrong use of it.

💡 Note: If the Dictionary that the dict.values() method is operating on is empty, an empty list will be returned.

Basic Example

An example of a Python dictionary values() method call:

items = {'pens': 5, 'pencils': 6, 'desks': 5, 'notebooks': 8}
print(items.values())
# dict_values([5, 6, 5, 8])

This example shows the dict.values() method returning a list of values of all the keys in a dictionary.

Sum Over All Values in a Dictionary with dict.values()

Example using the dict.values() and the sum() function to count all the key’s values:

grocery_items = {'kiwis': 2, 'dragon_fruit': 3, 
                 'ground_nuts': 12, 'eggs': 18}
item_quantities = grocery_items.values()
 
print('total quantity of grocery items: ', sum(item_quantities))
# total quantity of grocery items:  35

In this example, the dict.values() method returns an iterable of the quantities of each grocery item from the grocery_items dictionary.

The sum() function is then applied to the list of quantities, which then returns the total quantity of grocery items.

Get List of Values with dict.values()

Example on how to get a list of values from a Python Dictionary using the dict.values() method:

vehicle_lot = {'cars': 30, 'trucks': 20, 'semis': 5}
list(vehicle_lot.values())
# [30, 20, 5]

The dict.values() method operates on the vehicle_lot dictionary and returns a view object of the values, then the list() function is then applied to the view object, which in turn converts the view object to an actual list of values.