Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dict+dict
#1
if abc and xyz are dictionaries, i can do abc.update(xyz) and have a combined dictionary as a result. but i sometimes don't want to modify either source dictionary. it would be nice if + could do this for me, like abc+xyz.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
You can use the unpacking operator ** to do the job.

abc = {'abc': 123}
xyz = {'xyz': 456}
pdq = {**abc, **xyz}
print (pdq)
Output:
{'abc': 123, 'xyz': 456}
Reply
#3
One rarely needs to mutate anything ;).

Another option is to use toolz.dicttoolz.merge (https://toolz.readthedocs.io/en/latest/a...oolz.merge). There's a lot of good stuff in Toolz.
Reply
#4
https://docs.python.org/3/library/stdtyp...types-dict Wrote:d | other
Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys.

New in version 3.9.
abc = {'abc': 123}
xyz = {'xyz': 456}
pdq = abc | xyz
print(abc)
print(xyz)
print(pdq)
Output:
{'abc': 123} {'xyz': 456} {'abc': 123, 'xyz': 456}
Reply
#5
Sometimes it is important to retain key-value pairs which are first encountered. For that ChainMap can be used:

>>> from collections import ChainMap
>>> d = {'a': 1, 'b': 2}
>>> d_2 = {'a': 11, 'b':22}
>>> d | d_2                   # next key value overwrites previous    
{'a': 11, 'b': 22}
>>> dict(ChainMap(d, d_2))
{'a': 1, 'b': 2}              # first value retained
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#6
i'm still coding for 3.6 and d1|d2 does not work. but {**d1,**d2} does. thanks!
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  why do we need dict.get() ? Skaperen 10 1,821 May-13-2023, 02:28 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020