merge two dictionnary with the same structure in python

You can merge two dictionaries in Python using the update() method, which modifies the dictionary in place by adding keys and values from another dictionary. Here's an example:

main.py
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1.update(dict2)
print(dict1)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
127 chars
5 lines

In this example, we merged dict2 into dict1 using the update() method.

If you want to create a new dictionary that merges the contents of two dictionaries without modifying either of them, you can use a dictionary comprehension:

main.py
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
146 chars
5 lines

In this example, we merged dict1 and dict2 into a new dictionary merged_dict using a dictionary comprehension that combines two dictionaries using the ** operator.

gistlibby LogSnag