The dict.values() method returns a dict_values dynamic view object containing all mapped values in the dictionary in insertion order.
Live View Linked to Source: Like dict.keys(), the dict_values object does not create a static detached copy. When values are modified, added, or removed in the underlying dictionary, the view object reflects those changes automatically.
The standard CPython signature for dict.values() is:
dictionary.values()
| Component | Type | Parameters? | Behavior & Description |
|---|---|---|---|
| Arguments | None | None | values() takes zero arguments. Passing parameters raises TypeError. |
| Return Value | dict_values |
— | A live, iterable view of values matching insertion order. Values can include duplicate items and unhashable objects (e.g. lists or dicts). |
The dict_values object provides a live window into the dictionary's values without copying them into an independent list:
inventory = {"apples": 50, "bananas": 30, "cherries": 75}
# Obtain the live view
stock_levels = inventory.values()
print("Initial values view:", stock_levels) # dict_values([50, 30, 75])
# Update an existing item and add a new one
inventory["bananas"] = 45
inventory["dates"] = 20
# The view immediately reflects both mutations
print("Updated values view:", stock_levels) # dict_values([50, 45, 75, 20])
Because dict_values is an iterable sequence, you can pass it directly to Python's built-in mathematical functions without pre-converting to a list:
test_scores = {"Ravi": 85, "Sara": 92, "Alex": 78, "Priya": 95}
total = sum(test_scores.values())
highest = max(test_scores.values())
lowest = min(test_scores.values())
average = total / len(test_scores.values())
print(f"Total: {total}") # 350
print(f"Highest: {highest}") # 95
print(f"Lowest: {lowest}") # 78
print(f"Average: {average}") # 87.5
Python provides three view objects for dictionaries. Understanding their differences is key to writing clean, idiomatic code:
| Method | Return Type | Unique Items Guaranteed? | Set Operations (&, |, -)? | Primary Engineering Role |
|---|---|---|---|---|
d.keys() |
dict_keys |
Yes (Keys are unique) | Yes (Implements Set protocol) | Schema validation, checking key existence, set comparisons. |
d.values() |
dict_values |
No (Can contain duplicates) | No (Raises TypeError) |
Aggregations (sum, max), value checks, histogram counts. |
d.items() |
dict_items |
Yes (Key component unique) | Yes (If values are hashable) | Iterating key-value pairs simultaneously in loops. |
Mathematical sets require elements to be unique and hashable. In Python, dictionary values can contain duplicate objects (e.g. three users with grade "A") or mutable, unhashable objects (e.g. lists or sub-dictionaries). Hence, Python disallows direct set operators on dict_values.
Be mindful of computational complexity when performing membership tests:
key in my_dict: Executes in O(1) constant time using the internal hash table.value in my_dict.values(): Executes in O(n) linear time because Python must sequentially scan every value until a match is found.cache = {f"user_{i}": i for i in range(100000)}
# Fast O(1) hash check
print("user_999" in cache) # Instantaneous
# Slower O(n) sequential scan across 100,000 values
print(999 in cache.values())
Quickly determine if any values are duplicated across keys by comparing the length of the values view against a set conversion:
def has_duplicate_values(d: dict) -> bool:
val_list = list(d.values())
return len(val_list) != len(set(val_list))
port_allocations_ok = {"web": 80, "ssl": 443, "ssh": 22}
port_allocations_conflict = {"web": 80, "api": 80, "ssl": 443}
print("Port conflict in ok?", has_duplicate_values(port_allocations_ok)) # False
print("Port conflict in bad?", has_duplicate_values(port_allocations_conflict)) # True
Find which key maps to a specific value without third-party packages:
def get_key_for_value(d: dict, target_val) -> str | None:
for k, v in d.items():
if v == target_val:
return k
return None
user_roles = {"admin": 1, "editor": 2, "viewer": 3}
print("Role with ID 2:", get_key_for_value(user_roles, 2)) # 'editor'
Calling my_dict.values()[0] raises TypeError: 'dict_values' object is not subscriptable. Convert to a list if positional indexing is required: list(my_dict.values())[0].
Attempting to run set operations like d1.values() & d2.values() raises TypeError: unsupported operand type(s) for &: 'dict_values' and 'dict_values'. Convert to sets first: set(d1.values()) & set(d2.values()).
Run this complete test harness verifying live updates, aggregations, duplicate detection, and reverse lookup:
class ValuesVerifier:
@staticmethod
def calculate_stats(data: dict) -> tuple[int, int, float]:
vals = data.values()
return sum(vals), max(vals), sum(vals) / len(vals)
@staticmethod
def contains_duplicate_values(data: dict) -> bool:
v = list(data.values())
return len(v) != len(set(v))
# Verification unit assertions
v = ValuesVerifier()
# Test 1: Math aggregations
total, highest, mean = v.calculate_stats({"a": 10, "b": 20, "c": 30})
assert total == 60
assert highest == 30
assert mean == 20.0
# Test 2: Duplicate detection
assert v.contains_duplicate_values({"a": 1, "b": 1}) is True
assert v.contains_duplicate_values({"a": 1, "b": 2}) is False
# Test 3: Live view updates
mapping = {"x": 100}
live_v = mapping.values()
mapping["y"] = 200
assert list(live_v) == [100, 200]
print("All dict.values() unit assertions passed successfully!")
Open in Google Colab View on GitHub
Run all dictionary values exercises interactively, test dynamic view synchronization, perform numeric aggregations, detect duplicate values, and practice reverse lookups in Google Colab.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.