How to save a dictionary to two independent objects in Python?

Asked

Viewed 55 times

3

Consider the following dictionaries:

dic1 = {'k1':'Ford','k2':'GM','k3':'Dodge'}
dic2 = {'k4':'Audi','k5':'Mercedes','k6':'VW'}
dic3 = {'k7':'Fiat','k8':'Mazda'}

The goal is to get two new dictionaries, so that dic4 is the union of dic1 and dic2

{'k1':'Ford','k2':'GM','k3':'Dodge','k4':'Audi','k5':'Mercedes','k6':'VW'}

and dic5 the union of dic1 and dic3

{'k1':'Ford','k2':'GM','k3':'Dodge','k7':'Fiat','k8':'Mazda'}

The issue here is to keep dic1, dic2 and dic3 unchanged so that they can be used again. At first I thought to do dic1.update(dic2), but then I would lose the original dictionary.

There is some way to store dic1 in two objects with different names (for example dicx and dicy) and then only work with them to assemble dic4 and dic5 dictionaries?

2 answers

4


An alternative is create a copy of dic1 and then do the update in the copy:

dic1 = {'k1':'Ford','k2':'GM','k3':'Dodge'}
dic2 = {'k4':'Audi','k5':'Mercedes','k6':'VW'}
dic3 = {'k7':'Fiat','k8':'Mazda'}

dic4 = dic1.copy()
dic4.update(dic2)

dic5 = dic1.copy()
dic5.update(dic3)

Or else:

dic4 = dict(dic1)
dic4.update(dic2)

dic5 = dict(dic1)
dic5.update(dic3)

Thereby, dic1, dic2 and dic3 remain unchanged.

Remembering that copy returns a Shallow copy - this can make a difference depending on the type of object you have in the dictionary, read here to better understand.


Another option, pointed out by @Miguel us comments:

dic4 = { **dic1, **dic2 }
dic5 = { **dic1, **dic3 }

Finally, from Python 3.9 it is possible to use the operator |, creating a new dictionary containing the keys of both operands:

dic1 = {'k1':'Ford','k2':'GM','k3':'Dodge'}
dic2 = {'k4':'Audi','k5':'Mercedes','k6':'VW'}
dic3 = {'k7':'Fiat','k8':'Mazda'}

dic4 = dic1 | dic2

dic5 = dic1 | dic3
  • Hello @hkotsubo https://ideone.com/RbRe7T, only two alternatives, if python3.5+

  • 1

    @Miguel I think is worth an answer, huh :-) (mainly the first option, I did not know it was possible)

  • 1

    Yes the second is basically your update, I won’t be able to answer because I’m on the phone and this is no use, but you can complement the answer if you feel appropriate

  • 1

    @Miguel OK, updated the reply, thank you!

  • Thank you for the reply!!

4

In Python 3.9 you have the pipe union "|".

dic4 = dic1 | dic2

In previous versions you can do the seginte:

dic4 = dic1.copy()
dic4.update(dic2)

The need for the copy is due to the fact that dictionaries are data structure of the type mutable. See more about changeable and immutable types here.

I hope it helps

  • 1

    Thank you for the reply!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.