How to merge two dictionaries?

Python provides several ways to combine two dictionaries into one.

Example:


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

Solution:

In Python 3.5+, you can use the ** unpacking operators. For Python 3.9+, you can use the | merge operator:


  merged_dict = dict1 | dict2
  

Beginner's Guide to Python