Merge Two Dictionaries in Python


To merge two dictionaries in Python, you can use several methods. Here are a few common ways:

1. Using the update() Method

The update() method updates the dictionary with elements from another dictionary object or from an iterable of key-value pairs.

# Using update() method
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

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

2. Using the ** Operator

The ** operator can be used to unpack dictionaries and merge them into a new dictionary.

# Using ** operator
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+)

Starting from Python 3.9, you can use the | operator to merge dictionaries.

# Using | operator (Python 3.9+)
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

You can also use dictionary comprehension to merge dictionaries.

# Using dictionary comprehension
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

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

Note: Each of these methods will merge the dictionaries, with values from the second dictionary overwriting those from the first in case of key conflicts.

References

  1. Python Dictionary with Examples

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.