How to merge Dictionaries with Python

There are lots of different ways to merge dictionaries in the Python.

Here are the methods you will learn about:

  • dict.update()
  • **
  • the | Union Operator

Let’s start with the update() method!

Using dict.update()

>>> first_dictionary = {"name": "Mike", "occupation": "Python Teacher"}
>>> second_dictionary = {"location": "Iowa", "hobby": "photography"}
>>> first_dictionary.update(second_dictionary)
>>> first_dictionary
{'name': 'Mike', 'occupation': 'Python Teacher', 'location': 'Iowa', 'hobby': 'photography'}

Merging with **

When you use the double-asterisk, it is sometimes called “unpacking”, “expanding” or “splatting” a dictionary.

Here is how you can use ** to merge 2 dictionaries:

>>> first_dictionary = {"name": "Mike", "occupation": "Python Teacher"}
>>> second_dictionary = {"location": "Iowa", "hobby": "photography"}
>>> merged_dictionary = {**first_dictionary, **second_dictionary}
>>> merged_dictionary
{'name': 'Mike', 'occupation': 'Python Teacher', 'location': 'Iowa', 'hobby': 'photography'}

Merging with the Union Operator

Here is how you can use the union operator to merge two dictionaries:

>>> first_dictionary = {"name": "Mike", "occupation": "Python Teacher"} >>> second_dictionary = {"location": "Iowa", "hobby": "photography"}>>> merged_dictionary = first_dictionary | second_dictionary>>> merged_dictionary{'name': 'Mike', 'occupation': 'Python Teacher', 'location': 'Iowa', 'hobby': 'photography'}
how to merge dictionaries in python


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

.

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.