Python
Published in Python
avatar
3 minutes read

Merging Two Dictionaries in a Single Expression

Merging Two Dictionaries in a Single Expression

In Python, you can easily merge two dictionaries into a single dictionary using a concise one-liner expression.

#1. Using the update() Method

The update() method is a straightforward way to merge two dictionaries. It modifies the dictionary in place, adding the key-value pairs from the second dictionary to the first one. If there are duplicate keys, the values from the second dictionary will overwrite the values from the first dictionary.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

dict1.update(dict2)
print(dict1)

Output:

{'a': 1, 'b': 3, 'c': 4}

In this example, the value for the key 'b' in dict1 was overwritten by the value '3' from dict2.

#2. Using Dictionary Unpacking (Python 3.5+)

Dictionary unpacking, also known as the double asterisk (**), is available in Python 3.5 and later versions. It allows you to merge two dictionaries into a new dictionary without modifying the original dictionaries.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

merged_dict = {**dict1, **dict2}
print(merged_dict)

Output:

{'a': 1, 'b': 3, 'c': 4}

Again, the value for the key 'b' comes from dict2, overwriting the value from dict1.

#3. Using dict() Constructor (Python 3.9+)

In Python 3.9 and later versions, you can use the dict() constructor with the | operator to merge dictionaries.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

merged_dict = dict1 | dict2
print(merged_dict)

Output:

{'a': 1, 'b': 3, 'c': 4}

The result is the same as using the update() method or dictionary unpacking.

#4. Handling Duplicate Keys

When merging dictionaries, it's essential to be aware of how duplicate keys are handled. The methods described above prioritize the values from the second dictionary. If a key exists in both dictionaries, the value from the second dictionary will overwrite the value from the first one.

#5. Caution with Nested Dictionaries

If the dictionaries being merged contain nested dictionaries, the above methods will only perform a shallow merge. That is, the nested dictionaries themselves will not be merged, and their references will be copied as-is to the merged dictionary. If you need a deep merge, you can use external libraries like deepmerge.

0 Comment