How to Replace Values in Python Dictionaries
Modifying dictionary values is a fundamental operation in Python.
This guide explores various techniques for replacing values in dictionaries, including in-place updates using update()
, dictionary unpacking, for loops, dictionary comprehensions, and the merge operator (|
and |=
). We'll cover replacing specific values, merging data from other dictionaries, and conditional replacements.
Replacing Values with dict.update()
The dict.update()
method modifies a dictionary in-place by adding or updating key-value pairs.
Updating with Another Dictionary
You can update a dictionary with values from another dictionary:
my_dict = {
'name': 'default',
'site': 'default',
'id': 1,
'topic': 'Python'
}
my_dict.update({'name': 'tom', 'site': 'tutorialreference.com'})
print(my_dict) # Output: {'name': 'tom', 'site': 'tutorialreference.com', 'id': 1, 'topic': 'Python'}
- Existing keys are updated with the new values.
- New keys from the updating dictionary are added.
- This method modifies the original dictionary directly, and doesn't return a new one.
Updating with Keyword Arguments
update()
can also accept keyword arguments, providing a concise way to update specific keys:
my_dict = {
'name': 'default',
'site': 'default',
'id': 1,
'topic': 'Python'
}
my_dict.update(name='tom', site='tutorialreference.com')
print(my_dict)
# Output: {'name': 'tom', 'site': 'tutorialreference.com', 'id': 1, 'topic': 'Python'}
Updating with an Iterable of Key-Value Pairs
my_dict = {
'name': 'default',
'site': 'default',
'id': 1,
'topic': 'Python'
}
my_dict.update(
[
('name', 'tom'),
('site', 'tutorialreference.com')
]
)
print(my_dict)
- You can also pass a list of tuples to the
update()
method.
Replacing Values with Dictionary Unpacking (**
)
Dictionary unpacking within a new dictionary literal provides a way to create a new dictionary with updated values, leaving the original unchanged:
my_dict = {
'name': 'default',
'site': 'default',
'id': 1,
'topic': 'Python'
}
my_dict = {**my_dict, 'name': 'tom', 'site': 'tutorialreference.com'}
print(my_dict) # Output: {'name': 'tom', 'site': 'tutorialreference.com', 'id': 1, 'topic': 'Python'}
**my_dict
unpacks the existing dictionary into the new dictionary literal.- If you specify a dictionary element with a key that is already present in the dictionary, its value will be replaced with the new value.
- Later key-value pairs override earlier ones if there are duplicate keys.
Replacing Values with a for
Loop
A for
loop offers explicit control over the replacement process, allowing for conditional updates:
my_dict = {
'name': 'default',
'site': 'default',
'id': 1,
'topic': 'Python'
}
for key, value in my_dict.items():
if value == 'default':
if key == 'name':
my_dict[key] = 'tom'
elif key == 'site':
my_dict[key] = 'tutorialreference.com'
print(my_dict) # Output: {'name': 'tom', 'site': 'tutorialreference.com', 'id': 1, 'topic': 'Python'}
- The code will only replace values that are exactly equal to
default
.
Replacing Values with the Dictionary Merge Operators (|
and |=
)
Python 3.9 introduced dictionary merge operators:
|
(Merge): Creates a new dictionary by merging two dictionaries.|=
(Update): Modifies a dictionary in-place, similar toupdate()
.
my_dict = {
'name': 'default',
'site': 'default',
'id': 1,
'topic': 'Python'
}
my_dict = my_dict | {'name': 'tom nolan', 'site': 'tutorialreference.com'}
print(my_dict)
# Output: {'name': 'tom nolan', 'site': 'tutorialreference.com', 'id': 1, 'topic': 'Python'}
- In this example a new dictionary is created where the values of the existing keys from
my_dict
are overwritten with the ones in the dictionary after the|
operator.
And here's an example with the update operator |=
:
my_dict = {
'name': 'default',
'site': 'default',
'id': 1,
'topic': 'Python'
}
my_dict |= {'name': 'tom nolan', 'site': 'tutorialreference.com'}
print(my_dict)
# Output: {'name': 'tom nolan', 'site': 'tutorialreference.com', 'id': 1, 'topic': 'Python'}
- This is an in-place operation and works similar to the
update()
method.
Replacing Values Based on Another Dictionary
To update values in one dictionary based on the contents of another, use a loop or a dictionary comprehension:
my_dict = {
'name': 'default',
'site': 'default',
'id': 1,
'topic': 'Python'
}
another_dict = {
'name': 'tom nolan',
'site': 'tutorialreference.com',
'abc': 'xyz',
'one': 'two',
}
for key, value in another_dict.items():
if key in my_dict:
my_dict[key] = value
print(my_dict)
# Output: {'name': 'tom nolan', 'site': 'tutorialreference.com', 'id': 1, 'topic': 'Python'}
- The for loop goes through the items of
another_dict
and checks if that key exists inmy_dict
using thein
operator. - If the key exists, the corresponding value will be updated in the first dictionary.
Replacing Values with Dictionary Comprehensions
Dictionary comprehensions provide a very concise way to create a new dictionary with modified values, based on an existing dictionary:
my_dict = {
'name': 'default',
'site': 'default',
'id': 1,
'topic': 'Python'
}
another_dict = {
'name': 'tom nolan',
'site': 'tutorialreference.com',
'abc': 'xyz',
'one': 'two',
}
my_dict = {
key: another_dict.get(key, value)
for key, value in my_dict.items()
}
print(my_dict)
# Output: {'name': 'tom nolan', 'site': 'tutorialreference.com', 'id': 1, 'topic': 'Python'}
- The
.get()
method will try to find the key frommy_dict
in theanother_dict
. - If a matching key is found, the dictionary comprehension will return the value of that key from
another_dict
. - If a matching key is not found, the expression will return the value of the current iteration from
my_dict
.