Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

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

Solution:

Using Python 3.5 and higher versions, you can merge 2 dictionaries into a single expression using the {**dict1, **dict2} syntax.

Here’s an example.


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

merged_dict = {**dict1, **dict2}

print(merged_dict)

Output:

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

However, if you're using Python 3.9 and later, you can also use the | operator. 

How?


  merged_dict = dict1 | dict2

Also, you can use the update() function, a built-in dict class method that allows you to update one dictionary with key-value pairs from another.

Here’s an example.


  #Define two dictionaries with common and unique keys
  dict1 = {'a': 1, 'b': 2, 'c': 3}
  dict2 = {'b': 4, 'd': 5}
  
  #Merge dictionaries using the update() method
  dict1.update(dict2)
  
  #Output the merged dictionary
  print(dict1)

Output:

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

Lastly, you can also use memory-efficient methods like ChainMap or itertools.chain() if your dictionary has large data sets.

Want to know more about Python? Check out our blogs!