DEV Community

Cover image for 2 ways to merge Python dictionaries
Renan Moura
Renan Moura

Posted on • Edited on • Originally published at renanmf.com

2 ways to merge Python dictionaries

There are basically two ways of merging two or more dictionaries in Python.

If you search randomly on the internet, you may find other approaches, but they are either inefficient computation-wise or just bad practices.

How to do it before Python 3.5

If you are using Python 2 or any version bellow Python 3.5, you have to use a two-step approach using the copy() and update() functions.

#initialize first dict
four_or_more_world_cups = {'Brazil': 5, 'Italy': 4, 'Germany': 4}

#initialize second dict
two_world_cups = {'Argentina':2, 'France':2, 'Uruguay': 2}

#copy first dict to a new third dict
top_six_world_cup_winners = two_world_cups.copy()

#update third dict with the second dict
top_six_world_cup_winners.update(four_or_more_world_cups)

print(top_six_world_cup_winners)
#output:
{'Brazil': 5, 'Germany': 4, 'Uruguay': 2, 'Italy': 4, 'Argentina': 2, 'France': 2}
Enter fullscreen mode Exit fullscreen mode

Python 3.5 and beyond

As of Python 3.5, the merging notation is greatly simplified and the whole thing can be done in a single command.

#initialize first dict
four_or_more_world_cups = {'Brazil': 5, 'Italy': 4, 'Germany': 4}

#initialize second dict
two_world_cups = {'Argentina':2, 'France':2, 'Uruguay': 2}

#merging dicts in a third dict
top_six_world_cup_winners = {**two_world_cups, **four_or_more_world_cups}

print(top_six_world_cup_winners)
#output:
{'Argentina': 2, 'France': 2, 'Uruguay': 2, 'Brazil': 5, 'Italy': 4, 'Germany': 4}
Enter fullscreen mode Exit fullscreen mode

That's it! If you want to know more about Python dictionaries, check out my post on
Python Dictionary: a quick reference.

Originally published at renanmf.com

Top comments (0)