Python Forum

Full Version: merging dictionaries
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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.
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}
(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.