merge a dictionnary with another dictionnary in python

There are different ways to merge two dictionaries in Python. Here are a few examples:

  1. Using the update() method:
main.py
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)
# Output: {'a': 1, 'b': 3, 'c': 4}
118 chars
6 lines

In this example, the update() method takes a dictionary as an argument and adds its key-value pairs to the calling dictionary (dict1 in this case). If there are common keys between the two dictionaries, the values of the calling dictionary will be overwritten by the values of the argument dictionary.

  1. Using the double asterisk (**) operator:
main.py
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
# Output: {'a': 1, 'b': 3, 'c': 4}
137 chars
6 lines

In this example, we use the ** operator to unpack the dictionaries and create a new dictionary (merged_dict) with all the key-value pairs. If there are common keys between the two dictionaries, the values of the second dictionary (dict2 in this case) will overwrite the values of the first dictionary (dict1).

  1. Using the dict() constructor:
main.py
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict(dict1, **dict2)
print(merged_dict)
# Output: {'a': 1, 'b': 3, 'c': 4}
139 chars
6 lines

In this example, we use the dict() constructor to create a new dictionary by merging dict1 and dict2. We pass dict1 as the first positional argument and use the ** operator to unpack dict2 as keyword arguments. If there are common keys between the two dictionaries, the values of the second dictionary (dict2 in this case) will overwrite the values of the first dictionary (dict1).

gistlibby LogSnag