How to update values in a dictionary in Python?
Published on Aug. 22, 2023, 12:17 p.m.
To update the values in a Python dictionary, you can use the update()
method or simply update the value using its corresponding key.
Here is an example of how to use the update()
method to update the values in a dictionary:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
my_dict.update({'key2': 'new_value2', 'key3': 'new_value3'})
# my_dict is now {'key1': 'value1', 'key2': 'new_value2', 'key3': 'new_value3'}
In this example, the update()
method is used to update the values of 'key2'
and 'key3'
in my_dict
.
Here is an example of how to update the value of a specific key in a dictionary using assignment:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
my_dict['key2'] = 'new_value2'
# my_dict is now {'key1': 'value1', 'key2': 'new_value2', 'key3': 'value3'}
In this example, the value of 'key2'
in my_dict
is updated directly using assignment.
Both methods are effective for updating values in a dictionary, but the choice between them typically depends on the specific use case and personal preference.