Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python dict.values() method

Reference for Python dict.values(): a live view of a dictionary's values, iteration, membership tests, converting to a list, and what views cannot do.

The values() method returns a view object of all values in a dictionary, in insertion order. A view is not a copy: it reflects later changes to the dictionary. You can loop over it, test membership with in, take its len(), and pass it to functions such as sum(), max() and sorted().

Use it when you care about the values and not the keys, for example totalling prices or checking whether any value matches.

Python
prices = {"tea": 3, "cake": 5}
sum(prices.values())   # 8

Try it

Python Working with values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Views are live

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
dict.values()
Name Description
(none) The method takes no arguments.

Return value: a dict_values view of the values.

Usage notes

  • A view, not a list. It cannot be indexed or sliced. Use list(d.values()) when you need a list or a snapshot.
  • It is live. Adding, changing or deleting items changes what the view shows. Changing the dictionary's size while looping over the view raises RuntimeError.
  • Order matches the keys. d.keys(), d.values() and d.items() iterate in the same insertion order, so zip(d.keys(), d.values()) equals d.items().
  • Membership is a linear scan. x in d.values() compares against each value (using ==), unlike key in d, which is a fast hash lookup.
  • Values need not be unique or hashable. Unlike keys(), a values view is not set-like, so d1.values() & d2.values() does not work.
  • Comparing views: two values() views are never equal to each other by content, even for the same dictionary; compare list(...) or sorted(...) instead.
  • Reverse iteration works since Python 3.8: reversed(d.values()).