Python dict union

How do you calculate the union of two dict objects in Python, where the pair (key, value) present as a result of iff key is in or dict (unless there are duplicates)?

For example, the union of {'a' : 0, 'b' : 1} and {'c' : 2} is equal to {'a' : 0, 'b' : 1, 'c' : 2} .

You can do this without changing the dict input. An example of where this is useful: Get a list of all the variables currently in the area and their values

+49
python dictionary idioms associative-array set-operations
Mar 22 2018-12-22T00:
source share
4 answers

This question contains an idiom. You use one of the arguments as keyword arguments to the dict() constructor:

 dict(y, **x) 

Duplicates are allowed in favor of the value at x ; eg

 dict({'a' : 'y[a]'}, **{'a', 'x[a]'}) == {'a' : 'x[a]'} 
+53
Mar 22 '12 at 9:37
source share

You can also use the update dict method, for example

 a = {'a' : 0, 'b' : 1} b = {'c' : 2} a.update(b) print a 
+50
Mar 22 2018-12-12T00:
source share

Two dictionaries

 def union2(dict1, dict2): return dict(list(dict1.items()) + list(dict2.items())) 

n dictionaries

 def union(*dicts): return dict(itertools.chain.from_iterable(dct.items() for dct in dicts)) 
+16
Oct 17
source share

If you want both dicts to remain independent and updated, you can create one object that queries both dictionaries in its __getitem__ method (and implements get , __contains__ and the other matching method as necessary).

An example of minimalism might be this:

 class UDict(object): def __init__(self, d1, d2): self.d1, self.d2 = d1, d2 def __getitem__(self, item): if item in self.d1: return self.d1[item] return self.d2[item] 

And it works:

 >>> a = UDict({1:1}, {2:2}) >>> a[2] 2 >>> a[1] 1 >>> a[3] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in __getitem__ KeyError: 3 >>> 
+4
Mar 22 '12 at 11:24
source share



All Articles