How to merge two dictionaries in Python?

Published on Aug. 22, 2023, 12:17 p.m.

There are several ways to merge two dictionaries in Python, depending on your specific use case. Here are a few examples:

  1. Using the update() method: You can use the update() method to add all the key-value pairs from one dictionary to another:
dict1 = {'key1': 'value1', 'key2': 'value2'}
dict2 = {'key3': 'value3', 'key4': 'value4'}
dict1.update(dict2)

After this code block, dict1 will be the merged dictionary, containing all the key-value pairs from both dict1 and dict2.
2. Using the ** operator: You can use the ** operator to unpack the values of two dictionaries and create a new, merged dictionary:

dict1 = {'key1': 'value1', 'key2': 'value2'}
dict2 = {'key3': 'value3', 'key4': 'value4'}
merged_dict = {**dict1, **dict2}

After this code block, merged_dict will be a new dictionary containing all the key-value pairs from both dict1 and dict2.
3. Using the | operator: In Python 3.9 or newer, you can use the | operator to merge two dictionaries, like this:

dict1 = {'key1': 'value1', 'key2': 'value2'}
dict2 = {'key3': 'value3', 'key4': 'value4'}
merged_dict = dict1 | dict2

After this code block, merged_dict will be a new dictionary containing all the key-value pairs from both dict1 and dict2.

Choose the method that suits your specific use case and Python version.

Tags: