This question already has an answer here:
How do you calculate the union of two dict
objects in Python, where a (key, value)
pair is present in the result iff key
is in
either dict (unless there are duplicates)?
For example, the union of {'a' : 0, 'b' : 1}
and {'c' : 2}
is {'a' : 0, 'b' : 1, 'c' : 2}
.
Preferably you can do this without modifying either input dict
. Example of where this is useful: Get a dict of all variables currently in scope and their values
Two dictionaries
n dictionaries
If you need both dicts to remain independent, and updatable, you can create a single object that queries both dictionaries in its
__getitem__
method (and implementget
,__contains__
and other mapping method as you need them).A minimalist example could be like this:
And it works:
This question provides an idiom. You use one of the dicts as keyword arguments to the
dict()
constructor:Duplicates are resolved in favor of the value in
x
; for exampleYou can also use
update
method of dict like