How do you merge two dictionaries in Python?

Merging two dictionaries in Python can be achieved in multiple ways, depending on your Python version and preference. Here’s a breakdown of the most common methods:


1. Using the update() Method (Available in All Versions)

The update() method adds the key-value pairs from one dictionary to another. If keys overlap, the values in the second dictionary overwrite those in the first.

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

dict1.update(dict2)  # Modifies dict1 in place
print(dict1)  # Output: {'a': 1, 'b': 3, 'c': 4}

2. Using the {**dict1, **dict2} Syntax (Python 3.5+)

You can use unpacking to merge dictionaries. This creates a new dictionary without modifying the originals.

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

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

3. Using the | Operator (Python 3.9+)

The | operator provides a concise way to merge dictionaries and returns a new dictionary. This is similar to unpacking but more readable.

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

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

4. Using Dictionary Comprehension

For more control, you can use dictionary comprehension to merge dictionaries manually.

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

merged_dict = {key: value for d in [dict1, dict2] for key, value in d.items()}
print(merged_dict)  # Output: {'a': 1, 'b': 3, 'c': 4}

5. Using a Third-Party Library (collections.ChainMap)

The ChainMap class from the collections module groups multiple dictionaries together. It does not create a new dictionary but provides a single view for lookup.

from collections import ChainMap

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

merged = ChainMap(dict2, dict1)  # dict2 takes precedence for overlapping keys
print(dict(merged))  # Output: {'a': 1, 'b': 3, 'c': 4}

Key Points

  • Use update() if you want to modify an existing dictionary.
  • Use {**dict1, **dict2} or | if you need a new dictionary.
  • The ChainMap approach is efficient for lookups but not for creating a standalone dictionary.

Let me know which method suits your needs, or if you’d like to see an example tailored to your use case!

My Thought

Your email address will not be published. Required fields are marked *

Our Tool : hike percentage calculator