dict. values()
Returns a view of the dictionary values, ready for loops, sums, and lookups.
- Returns
- A
dict_valuesview object. - Changes the original
- No
Example
#scores = {"Emma": 92, "Jack": 78, "Mia": 85}
print(scores.values())
print(sum(scores.values()))
print(max(scores.values()))
print(78 in scores.values())Definition and usage
#The values() method returns a view of all the dictionary values in the order their keys were added. Like the keys view, it shows the content live, so it reflects every later change to the dictionary.
It's most often passed to functions that process a whole collection: sum(), max(), min(), sorted(), or any(). That lets you add up every student's points, for example, in a single line.
Unlike keys, values can repeat and don't need to be immutable, so the values view does not support set operations. Checking x in dict.values() works, but it scans the values one by one, so it's much slower than looking up a key on large dictionaries.
Syntax
#dict.values()More examples
#levels = {"Emma": 3, "Jack": 2, "Mia": 3, "Ivy": 1}
average = sum(levels.values()) / len(levels)
print(f"Average level: {average:.2f}")
print(sorted(set(levels.values())))scores = {"Emma": 92, "Jack": 78, "Mia": 85}
print(max(scores.values()))
print(max(scores, key=scores.get))Good practices
#- The values view alone does not say which key a given value belongs to. When you need both, use
items()ormax(dict, key=dict.get). - If you often search by value, build a reversed dictionary where the values become keys. Lookups are then instant.
Related entries
#- dict.keys()Returns a view of the dictionary's keys that always reflects its current contents.
- dict.items()Returns a view of (key, value) pairs, the most convenient way to loop over a dictionary.
- sum()Adds together all the numbers in a collection.
- max()Returns the largest item in a collection, or the largest of several arguments.
- sorted()Returns a new, sorted list built from the items of any collection.
Spotted a mistake or missing an example? Write to us.