Python
dictionaries
merge
programming
coding

How do I merge two dictionaries in a single expression in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Python, dictionaries hold data in key-value pairs, making them one of the most versatile data structures available. Merging two dictionaries is a common task in Python, and it can often be done succinctly in a single expression. This article delves into the methods available for merging dictionaries, explaining the mechanics behind each and offering practical examples.

Dictionary Merging in Python

Method 1: Using the update() Method

The update() method allows you to merge two dictionaries by adding the key-value pairs from one dictionary into another.

python
1dict1 = {'a': 1, 'b': 2}
2dict2 = {'b': 3, 'c': 4}
3
4dict1.update(dict2)
5print(dict1)  # Output: {'a': 1, 'b': 3, 'c': 4}

Explanation: In this method, dict1 is updated with dict2. If dict2 has keys that are already in dict1, their values will overwrite those in dict1.

Method 2: Dictionary Unpacking (Python 3.5+)

With the advent of Python 3.5, the ** operator allows for a more pythonic way to merge dictionaries via unpacking.

python
1dict1 = {'a': 1, 'b': 2}
2dict2 = {'b': 3, 'c': 4}
3
4merged_dict = {**dict1, **dict2}
5print(merged_dict)  # Output: {'a': 1, 'b': 3, 'c': 4}

Explanation: Here, the ** operator unpacks key-value pairs from dict1 and dict2 into a new dictionary. If there are overlapping keys, values from dict2 prevail.

Method 3: The | Operand (Python 3.9+)

Starting with Python 3.9, the | operand provides a clean and efficient way to merge dictionaries.

python
1dict1 = {'a': 1, 'b': 2}
2dict2 = {'b': 3, 'c': 4}
3
4merged_dict = dict1 | dict2
5print(merged_dict)  # Output: {'a': 1, 'b': 3, 'c': 4}

Explanation: The use of the | operand produces a new dictionary combining both dictionaries, with dict2 values overwriting dict1's in the event of key conflicts.

Method 4: Using collections.ChainMap

collections.ChainMap lets you combine multiple dictionaries while retaining the dictionaries as separate entities.

python
1from collections import ChainMap
2
3dict1 = {'a': 1, 'b': 2}
4dict2 = {'b': 3, 'c': 4}
5
6chain_map = ChainMap(dict1, dict2)
7print(chain_map)  # Output: ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4})
8print(chain_map['b'])  # Output: 2

Explanation: ChainMap creates a single view over a sequence of dictionaries. When retrieving a key, it returns the first occurrence found in the maps.

Considerations for Merging

  1. Key Conflicts: update(), |, and dictionary unpacking all prioritize the last dictionary's value if keys are duplicated.
  2. Memory Efficiency: ChainMap does not physically combine dictionaries but keeps a logical combination, which can be more memory-efficient.
  3. Immutability: Using update() alters the dictionary in place; the other methods create a new dictionary.

Summary Table

MethodVersionIn-Place?Key Conflict ResolutionImmutability
update()-YesLater dictionary keys overwriteAlters the first dictionary
Dictionary Unpacking (**)3.5+NoLater dictionary keys overwriteCreates a new dictionary
| Operand3.9+NoLater dictionary keys overwriteCreates a new dictionary
collections.ChainMap-NoFirst occurrence is retainedCreates a new ChainMap object

Additional Details

Custom Merging Logic

For scenarios where you need custom behavior when resolving key conflicts, consider using dictionary comprehension or functions such as functools.reduce.

python
1dict1 = {'a': 1, 'b': 2}
2dict2 = {'b': 3, 'c': 4}
3
4merged_dict = {key: dict2.get(key, dict1.get(key)) for key in set(dict1) | set(dict2)}
5print(merged_dict)  # Output: {'a': 1, 'b': 3, 'c': 4}

Performance Considerations

For large dictionaries, consider the performance impact. update(), being in-place, may have better performance compared to creating new structures.

In summary, the method you pick depends on your specific requirements such as performance considerations, Python version in use, and whether you need an immutable result. With this arsenal of techniques, you can efficiently and effectively merge dictionaries in Python.


Course illustration
Course illustration

All Rights Reserved.