
We will introduce 9 dict methods that beginners should learn.
Table of Contents(目次)
- keys() – Retrieve all keys in a dict
- values() – Retrieve all values in a dict
- items() – Retrieve key-value pairs in a dict
- update() – Add or update elements
- setdefault() – Add a value if the key does not exist
- get() – Safely retrieve a value for a specified key
- dict.fromkeys() – Generate a dict from an iterable
- pop() – Remove a specified element and return its value
- popitem() – Remove and retrieve the last added element
keys() – Retrieve all keys in a dict
The keys()
method retrieves the key information from a dict.
my_profile = {'name': 'Nico', 'age': 10}
keys = my_profile.keys()
print(keys) # dict_keys(['name', 'age'])
print(type(keys)) # <class 'dict_keys'>
When executing the code above, it returns dict_keys(['name', 'age'])
, confirming that the keys of the variable "my_profile" have been retrieved. Checking the data type returns "dict_keys", which shows that it is different from a list.
Although the output of a "dict_keys" object looks similar to a list, it is more memory-efficient and has other advantages.
Since "dict_keys" is not a list, you cannot use list methods on it. You also cannot access elements using indexes like keys[n]
. However, this data can be converted into a list, after which you can edit each element.
(Type conversion of data structures will be explained in a dedicated lecture.)
Additionally, since “dict_keys” can be used in a for loop without converting it to a list, the keys()
method is used when you want to perform iterative processing using the key information of the dictionary.
(For loops will be covered in a dedicated lecture.)
The same applies to the data types returned by the values()
and items()
methods.
values() – Retrieve all values in a dict
The values()
method retrieves the value information from a dict.
my_profile = {'name': 'Nico', 'age': 10}
values = my_profile.values()
print(values) # dict_values(['Nico', 10])
print(type(values)) # <class 'dict_values'>
When executing the code above, it returns dict_values(['Nico', 10])
, confirming that the values of the variable "my_profile" have been retrieved. Checking the data type returns "dict_values". "dict_values" shares the same characteristics as a "dict_keys" object.
items() – Retrieve key-value pairs in a dict
The items()
method retrieves key and value pairs from a dict.
my_profile = {'name': 'Nico', 'age': 10}
items = my_profile.items()
print(items) # dict_items([('name', 'Nico'), ('age', 10)])
print(type(items)) # <class 'dict_items'>
When executing the code above, it returns dict_items([('name', 'Nico'), ('age', 10)])
, confirming that each (key, value)
in the variable "my_profile" has been retrieved. Checking the data type returns "dict_items", which shares the same characteristics as a "dict_keys" object.
update() – Add or update elements
The update()
method merges elements from another dict. If both dicts have a common key, the information from the dict provided as an argument will overwrite the original.
my_profile = {'name': 'Nico', 'age': 10}
add_profile = {'age':99, 'friends': ['Emma', 'Jack']}
my_profile.update(add_profile)
print(my_profile) # {'name': 'Nico', 'age': 99, 'friends': ['Emma', 'Jack']}
The updated "my_profile" has its "age" updated to 99
and "friends" added.
update()
modifies the original dict. If you want to create a new dict with merged elements without updating the original dict, consider using the merge (|) operator.
setdefault() – Add a value if the key does not exist
Overview of setdefault()
The setdefault()
method behaves as follows:
- If the specified key does not exist, it adds the new key to the dict.
- If the specified key already exists, it does nothing.
The setdefault()
method is useful when (1) processing cannot continue unless a specific key exists, and (2) if the key already exists, you do not want to modify its value.
Behavior when the key exists
When the key exists, nothing is changed. The following code does not change anything because the variable "my_profile" already contains 'name'
.
my_profile = {'name': 'Nico', 'age': 10}
my_profile.setdefault('name')
print(my_profile) # {'name': 'Nico', 'age': 10}
Behavior when the key does not exist
If the key does not exist, the specified key is added. In the following code, since the variable "my_profile" does not contain 'friends'
, the key is added. By default, None
is set as the value. None
is a special object in Python that indicates no value exists.
my_profile = {'name': 'Nico', 'age': 10}
my_profile.setdefault('friends')
print(my_profile) # {'name': 'Nico', 'age': 10, 'friends': None}
Default value when the key does not exist
You can specify the default value when adding a key. Use the format setdefault(key, default_value)
.
my_profile = {'name': 'Nico', 'age': 10}
my_profile.setdefault('friends', [])
print(my_profile) # {'name': 'Nico', 'age': 10, 'friends': []}
The code above specifies an empty list ([]
) as the value when 'friends'
does not exist.
Confirming the behavior for existing and non-existing keys
Let’s check how the behavior changes depending on whether 'friends'
exists or not.
# When 'friends' exists
my_profile = {'name': 'Nico', 'age': 10, 'friends': ['Jack']}
my_profile.setdefault('friends', [])
my_profile['friends'].append('Emma')
print(my_profile) # {'name': 'Nico', 'age': 10, 'friends': ['Jack', 'Emma']}
# When 'friends' does not exist
my_profile = {'name': 'Nico', 'age': 10}
my_profile.setdefault('friends', [])
my_profile['friends'].append('Emma')
print(my_profile) # {'name': 'Nico', 'age': 10, 'friends': ['Emma']}
By writing code like the above, you can safely execute append('Emma')
on the list in the variable "my_profile" regardless of whether 'friends'
exists or not, without causing errors.
In line 10, if the dict does not have 'friends'
, it would raise a KeyError, and if the value of 'friends'
is not a list, the append('Emma')
call would also raise an error. Therefore, ensuring data existence beforehand with setdefault()
is very important.
Difference from directly adding key-value pairs
A dict can add a new key: value
pair using the format dict[key] = value
when the key does not exist. What is the difference from setdefault()
? Let’s first check the behavior when 'friends'
does not exist.
# When 'friends' does not exist
my_profile = {'name': 'Nico', 'age': 10}
my_profile['friends'] = []
my_profile['friends'].append('Emma')
print(my_profile) # {'name': 'Nico', 'age': 10, 'friends': ['Emma']}
When 'friends'
does not exist, the result is the same as with the setdefault()
method. Adding the new pair 'friends': []
behaves the same as setdefault('friends', [])
, and the append('Emma')
operation works without issues.
Next, let’s check the behavior when 'friends'
already exists.
# When 'friends' exists
my_profile = {'name': 'Nico', 'age': 10, 'friends': ['Jack']}
my_profile['friends'] = []
my_profile['friends'].append('Emma')
print(my_profile) # {'name': 'Nico', 'age': 10, 'friends': ['Emma']}
When 'friends'
exists, the result differs from the setdefault()
method.
This code updates the value of 'friends': ['Jack']
defined in the variable "my_profile" to an empty list ([]
) with my_profile['friends'] = []
. In the following line, 'Emma'
is added to the list, but 'Jack'
is no longer present.
The pattern of “do nothing if the key exists, otherwise add it” is common, so knowing the setdefault()
method is useful.
(* However, if you want to forcibly reset it to an empty list ([]
), you will need to use the dict[key] = []
format.)
get() – Safely retrieve a value for a specified key
The get()
method returns the value corresponding to a dict key. Unlike the usual var = dict[key]
, which raises an error if the key does not exist, get()
will return a default value instead of raising an error.
my_profile = {'name': 'Nico', 'age': 10}
friends = my_profile.get('friends')
print(friends) # None
As shown above, attempting to retrieve the non-existent 'friends'
with get()
does not raise an error but returns None
.
You can also specify a default value for get()
. Use the format get(key, default_value)
.
my_profile = {'name': 'Nico', 'age': 10}
friends = my_profile.get('friends', [])
print(friends) # []
The example above specifies an empty list ([]
) as the default value.
The get()
method is useful in scenarios where you are unsure whether a key exists, and you want to continue processing without errors by returning a default value.
dict.fromkeys() – Generate a dict from an iterable
The dict.fromkeys()
method creates a dict by taking keys from an iterable object like a list or tuple. The specified default value is set as the value.
items = ['Apple', 'Banana', 'Orange'] # List of products
inventory = dict.fromkeys(items, 0) # Initialize all stock to 0
print(inventory) # {'Apple': 0, 'Banana': 0, 'Orange': 0}
The above code shows the initial setup of a program for managing product inventory.
First, the variable "items" stores the list of products. Next, dict.fromkeys(items, 0)
generates a dict where the initial stock value 0
is set as the value for each product. This is useful when you want to assign the same initial value to many keys.
* If the number of keys is small and clearly defined, you do not need to use dict.fromkeys()
. You can simply initialize it directly as shown below:
inventory = {
'Apple': 0,
'Banana': 0,
'Orange': 0
}
(Modern text editors and AI code completion have made this type of initialization easier, even if you need to write a lot of similar code compared to the past.)
pop() – Remove a specified element and return its value
The pop()
method removes the key from the dict if it exists and returns its value.
The behavior of pop()
changes depending on whether the key exists in the dict and whether a default value is provided:
- pop(key)
- If the key exists, remove it from the dict and return its value.
- If the key does not exist, a KeyError is raised.
- pop(key, default_value)
- If the key exists, remove it from the dict and return its value.
- If the key does not exist, return the default_value.
The following code removes 'name'
from the dict. my_profile.pop('name')
removes 'name': 'Nico'
from the variable "my_profile" and assigns the value ('Nico'
) to the variable "result".
my_profile = {'name': 'Nico', 'age': 10}
result = my_profile.pop('name')
print(my_profile) # {'age': 10}
print(result) # Nico
If the specified key does not exist in the dict and no default value is provided, pop()
raises an error.
my_profile = {'name': 'Nico', 'age': 10}
result = my_profile.pop('zzz') # Error
If a default value is provided to pop()
, then even when the specified key does not exist in the dict, no error is raised, and the default value is assigned to the variable "result". The contents of the variable "my_profile" remain unchanged.
my_profile = {'name': 'Nico', 'age': 10}
result = my_profile.pop('zzz', 0)
print(my_profile) # {'name': 'Nico', 'age': 10}
print(result) # 0
popitem() – Remove and retrieve the last added element
The popitem()
method removes and returns the last (key, value)
pair that was added to the dict.
my_profile = {'name': 'Nico', 'age': 10}
result = my_profile.popitem()
print(my_profile) # {'name': 'Nico'}
print(result) # ('age', 10)
When executing the above code, ('age', 10)
is removed from the variable "my_profile", and that pair is assigned to the variable "result".
If no elements are available to remove, the popitem()
method raises a KeyError. To avoid errors, check in advance whether the dict contains elements. (We will cover if
statements in the section on conditional branching.)
my_profile = {}
result = None
if my_profile:
result = my_profile.popitem()
print(my_profile) # {}
print(result) # None