How to merge two dictionaries in Python?

 If you want merge two dictionaries without affecting the original ones, you could do the following:

x = {'a':2, 'b':1}

y = {'b':3, 'c':33}

z = x.copy() # makes a shallow copy of x

z.update(y)  # overides the values with the same key with y's value

{'a': 2, 'b': 3, 'c': 33}

or you can put those code in a function:

def merge_dict(d1, d2):

    z = d1.copy()

    z.update(d2)

    return z

z = merge_dict(x,y)

{'a': 2, 'b': 3, 'c': 33}

Since Python 3.5, you could just use the following single line to achieve this:

z = {**x, **y}

{'a': 2, 'b': 3, 'c': 33}

And also you coud pass literals notations in:

z = {**x, 'd':11,'e':33,**y}

{'a': 2, 'b': 3, 'd': 11, 'e': 33, 'c': 33}


Comments

Popular posts from this blog

How to write a slide puzzle game with Python and Pygame (2020 tutorial)

How to create a memory puzzle game with Python and Pygame (#005)

Introduction to multitasking with Python #001 multithreading (2020 tutorial)