update a dictionnary with another dictionnary in python

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.py
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)
83 chars
5 lines

Output:

main.py
{'a': 1, 'b': 3, 'c': 4}
25 chars
2 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.py
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
for key, value in dict2.items():
    if key not in dict1:
        dict1[key] = value
print(dict1)
148 chars
7 lines

Output:

main.py
{'a': 1, 'b': 2, 'c': 4}
25 chars
2 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