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.
prices = {"tea": 3, "cake": 5} sum(prices.values()) # 8
Try it
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.
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
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()andd.items()iterate in the same insertion order, sozip(d.keys(), d.values())equalsd.items(). - Membership is a linear scan.
x in d.values()compares against each value (using==), unlikekey in d, which is a fast hash lookup. - Values need not be unique or hashable. Unlike
keys(), a values view is not set-like, sod1.values() & d2.values()does not work. - Comparing views: two
values()views are never equal to each other by content, even for the same dictionary; comparelist(...)orsorted(...)instead. - Reverse iteration works since Python 3.8:
reversed(d.values()).
Related
dict.keys(),dict.items(),dict.get(),sum()- Lessons: Dictionaries, Dictionary methods