To update a dictionary with another dictionary in Python, you can use the .update()
method. This method merges the second dictionary into the first dictionary, replacing any existing values for keys that are in both dictionaries:
main.py83 chars5 lines
Output:
main.py25 chars2 lines
In this example, the value for key 'b'
in dict1
is replaced by the value from dict2
.
If you want to keep the original values and add the values from the second dictionary only for new keys, you can use a loop:
main.py148 chars7 lines
Output:
main.py25 chars2 lines
In this example, the value for key 'b'
in dict1
is not updated, and the value for key 'c'
is added to dict1
.
gistlibby LogSnag