values() returns a view of the dict's values, printed as dict_values([...]), in the same order as the keys. Like the other views it is live: later changes to the dict show up in it.
Values can repeat and do not have to be hashable, so a values view is not set-like. It is made for aggregating and scanning: sum(), max(), min(), counting, and in tests.
dict.values() is an instance method of the built-in dict type: call it on a dictionary with dot notation, such as expenses.values(...). No import is needed.
Syntax
Call it with no arguments and hand the view to a loop or an aggregate function.
python
view = d.values()
total = sum(d.values())
Call
What it does
{"a": 1, "b": 2}.values()
Returns dict_values([1, 2]).
sum({"a": 1, "b": 2}.values())
Returns 3.
2 in {"a": 1, "b": 2}.values()
Returns True.
A values view has no -, &, |, or ^; using them raises TypeError. Convert with set(d.values()) when you need unique values.
Method signatures
python
dict.values()
# returns: a dict_values view of the dict's values
Parameters
values() takes no parameters.
Return Value
Return Value
Description
dict_values
A live, read-only view of the values in insertion order. It supports len(), in, iteration, and reversed() (Python 3.8+).
Python Examples
Example 1 — Total a Monthly Budget
Sum the expenses, find the largest and smallest, and work out each category's share in percent.
python
expenses = {"rent": 1200, "food": 450, "transport": 90, "fun": 160}
amounts = expenses.values()
print(amounts)
print(sum(amounts), max(amounts), min(amounts))
print(round(sum(amounts) / len(amounts), 1))
print([round(a / sum(amounts) * 100) for a in amounts])
Assign through keys. A values view is read-only, so the loop writes each new price with prices[item] = .... Replacing values of existing keys during the loop is allowed.
Old view, new numbers.vals was created before the loop yet lists the discounted prices.
Identity trap. Two values views are never equal, even with identical contents, so the first comparison prints False.
Compare contents. Sorting both into lists compares the actual numbers and prints True.
Frequently Asked Questions
A dict_values view of the values in insertion order. It updates itself when the dict changes; wrap it in list() for a fixed copy.
Use sum(d.values()). max(d.values()) and min(d.values()) find the largest and smallest values.
Use value in d.values(). It scans the values one by one, so for frequent checks on large dicts keep a separate set.
Values views are compared by identity, and each call creates a new view object. Compare list(a.values()) == list(b.values()) instead.
Loop over the items: [k for k, v in d.items() if v == target]. Several keys can share a value, so you may get more than one.