Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
merging dictionaries
#1
i have 2 dictionaries A and B. i would like to use them merged without updating either. this would be like an OR operator for sets. but, of course, there is the ambiguity that dictionaries have, that sets do not have, of which value to use if a key is in both with different values. is there anything in Python that deals with this?
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
collections.ChainMap? ChainMap(A, B) with have all the keys from A and B, favoring A if the key is in both. Likewise, ChainMap(B, A) favors B if the key is in both. Note that if the key is in both, both values are stored, but only the one first found is returned. It depends on what you want to do if the key is in both dictionaries, which you did not specify.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
From 3.5 can use **.
>>> a = {'a':1, 'b': 2}
>>> b = {'c':10, 'd': 11}
>>> z = {**a, **b}
>>> z
{'a': 1, 'b': 2, 'c': 10, 'd': 11}
Reply
#4
(Nov-11-2018, 09:01 PM)ichabod801 Wrote: collections.ChainMap? ChainMap(A, B) with have all the keys from A and B, favoring A if the key is in both. Likewise, ChainMap(B, A) favors B if the key is in both. Note that if the key is in both, both values are stored, but only the one first found is returned. It depends on what you want to do if the key is in both dictionaries, which you did not specify.

i did not specify because i wasn't going to run into this. also, not being aware of collections.ChainMap, i didn't know it was doable to store both values. that might have some benefit in other cases if there is a way to get them all.
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
  merging three dictionaries Skaperen 3 1,986 Oct-20-2020, 10:06 PM
Last Post: Skaperen
  Merging Dictionaries - Optimum Style? adt 5 2,952 Oct-09-2019, 05:26 PM
Last Post: adt
  merging two dictionaries Skaperen 17 10,643 Oct-05-2017, 12:47 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