dict.keys() / dict.values() / dict.items()
| Since: | Python 2(2000) |
|---|
Methods that return the keys, values, and key-value pairs of a dictionary as view objects. They are commonly used for iteration with for loops and set operations.
Syntax
dict.keys() # Returns a view of all values in the dictionary. dict.values() # Returns a view of all key-value pairs (tuples) in the dictionary. dict.items()
Methods
| Method | Description |
|---|---|
| dict.keys() | Returns a view object (dict_keys) of all keys in the dictionary. The view automatically reflects any changes to the dictionary. |
| dict.values() | Returns a view object (dict_values) of all values in the dictionary. Duplicate values are all included. |
| dict.items() | Returns a view object (dict_items) of all (key, value) tuples in the dictionary. |
Sample Code
dict_keys_values_items.py
person = {
"name": "Gojo Satoru",
"age": 28,
"org": "Jujutsu High",
"email": "gojo_satoru@wp-p.info"
}
# Iterate over keys using keys().
print(list(person.keys())) # ['name', 'age', 'org', 'email']
for key in person.keys():
print(key, end=" ") # name age org email
# Note: "for key in person:" produces the same result.
# Iterate over values using values().
print(list(person.values())) # ['Gojo Satoru', 28, 'Jujutsu High', 'gojo_satoru@wp-p.info']
for value in person.values():
print(value, end=" ") # Gojo Satoru 28 Jujutsu High gojo_satoru@wp-p.info
# Iterate over key-value pairs using items() (a commonly used pattern).
for key, value in person.items():
print(f"{key}: {value}")
# name: Gojo Satoru
# age: 28
# org: Jujutsu High
# email: gojo_satoru@wp-p.info
# Calculate the total and average of scores using values().
scores = {"Math": 85, "English": 92, "History": 78, "Science": 88}
total = sum(scores.values())
average = total / len(scores)
print(f"Total: {total}, Average: {average:.1f}") # Total: 343, Average: 85.8
# Set operations using keys().
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"b": 20, "c": 30, "d": 40}
# Get the keys that exist in both dictionaries.
common_keys = dict1.keys() & dict2.keys()
print(common_keys) # {'b', 'c'}
# Get the keys that exist in dict1 but not in dict2.
only_in_dict1 = dict1.keys() - dict2.keys()
print(only_in_dict1) # {'a'}
# Practical example: transform a dictionary using items().
# Swap keys and values.
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
# Build a dictionary with only the entries that meet a condition.
filtered = {k: v for k, v in scores.items() if v >= 85}
print(filtered) # {'Math': 85, 'English': 92, 'Science': 88}
# View objects dynamically reflect changes to the dictionary.
d = {"x": 1}
keys_view = d.keys()
print(list(keys_view)) # ['x']
d["y"] = 2
print(list(keys_view)) # ['x', 'y'] (reflects the updated dictionary)
Running the code produces the following output:
python3 dict_keys_values_items.py
['name', 'age', 'org', 'email']
name age org email ['Gojo Satoru', 28, 'Jujutsu High', 'gojo_satoru@wp-p.info']
Gojo Satoru 28 Jujutsu High gojo_satoru@wp-p.info name: Gojo Satoru
age: 28
org: Jujutsu High
email: gojo_satoru@wp-p.info
Total: 343, Average: 85.8
{'c', 'b'}
{'a'}
{1: 'a', 2: 'b', 3: 'c'}
{'Math': 85, 'English': 92, 'Science': 88}
['x']
['x', 'y']
Common Mistakes
Common Mistake 1: Modifying a Dictionary During Iteration Raises an Error
Modifying a dictionary while iterating over a view object (keys, values, or items) raises a RuntimeError. To safely modify entries, iterate over a copy of the keys.
sorcerers = {'Gojo Satoru': 10, 'Itadori Yuji': 8, 'Fushiguro Megumi': 7}
# modifying the dictionary during iteration raises RuntimeError
try:
for name in sorcerers.keys():
if sorcerers[name] < 8:
del sorcerers[name] # RuntimeError: dictionary changed size during iteration
except RuntimeError as e:
print(f'Error: {e}')
The same logic can also be written as:
for name in list(sorcerers.keys()):
if sorcerers[name] < 8:
del sorcerers[name]
print(sorcerers) # {'Gojo Satoru': 10, 'Itadori Yuji': 8}
Common Mistake 2: Confusing View Objects with Lists
keys(), values(), and items() return view objects, not lists. Index access is not supported on view objects. Convert with list() when index access is needed.
sorcerers = {'Gojo Satoru': 10, 'Itadori Yuji': 8, 'Fushiguro Megumi': 7}
# index access on a view object is not supported
try:
first_key = sorcerers.keys()[0] # TypeError
except TypeError:
print('View objects do not support index access')
The same logic can also be written as:
keys_list = list(sorcerers.keys()) first_key = keys_list[0] print(first_key) # 'Gojo Satoru' # or use next() to get the first element first_key = next(iter(sorcerers.keys())) print(first_key) # 'Gojo Satoru'
Notes
keys(), values(), and items() each return a view object — a "window" into the dictionary that automatically updates whenever the dictionary changes. To use the result as a list, convert it with list().
Iterating over a dictionary directly with for key in dict: produces the same result as using keys(). Adding or removing entries from a dictionary while iterating over it raises a RuntimeError. If you need to modify the dictionary during iteration, first create a list of the keys (list(dict.keys())) and iterate over that instead.
Since Python 3.7, dictionaries maintain insertion order, so keys() returns keys in the order they were inserted. For safe key lookup in a dictionary, see dict.get() / dict.setdefault().
If you find any errors or copyright issues, please contact us.