2012-03-22 47 views
56

如何计算Python中两个dict对象的联合,其中(key, value)对存在于结果中iff keyin是否为dict(除非有重复项)?Python中的字典对象的联合

例如,{'a' : 0, 'b' : 1}{'c' : 2}的联合是{'a' : 0, 'b' : 1, 'c' : 2}

优选地,您可以在不修改任何输入dict的情况下执行此操作。的,其中,这是有用的例子:Get a dict of all variables currently in scope and their values

+2

这个问题与您在自己的答案中链接的问题不同? – 2012-03-22 09:46:25

+1

@RikPoggi:另一个问题,尽管它的标题是,询问** d2' *语法是什么。它恰好为这个问题提供了一个答案。 – 2012-03-23 04:52:39

回答

55

This question提供一个成语。您可以使用该类型的字典作为关键字参数的构造函数dict()之一:

dict(y, **x) 

重复赞成在x价值的解决;例如

dict({'a' : 'y[a]'}, **{'a', 'x[a]'}) == {'a' : 'x[a]'} 
+6

“简单胜过复杂”。 :)你应该使用'dict'的'update'成员函数。 – shahjapan 2012-08-06 18:51:20

+12

'tmp = dict(y); tmp.update(X); do_something(tmp)'更简单? – 2012-08-07 06:04:34

+6

@shahjapan这并不复杂,这是很好用的Python字典结构。这与更新不同(该解决方案没有更新任何内容)。 – lajarre 2012-09-13 09:09:39

53

您还可以使用字典的update方法类似

a = {'a' : 0, 'b' : 1} 
b = {'c' : 2} 

a.update(b) 
print a 
5

如果同时需要类型的字典保持独立,并更新,可以创建在其__getitem__查询两个字典的单个对象方法(并根据需要实施get,__contains__和其他映射方法)。

简约的例子可能是这样的:

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] 

而且它的工作原理:

>>> 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 
>>> 
18

两个字典

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

ň字典

def union(*dicts): 
    return dict(itertools.chain.from_iterable(dct.items() for dct in dicts)) 
+12

或者更可读,'dict(我在dct中为我的dct.items()中的dct)' – Eric 2013-05-13 09:12:57

+0

为什么要转换为list()? (dict1.items()+ dict2.items())' – kinORnirvana 2017-05-22 14:48:30

+1

@kinORnirvana在python 3中:a = {'x':1}; type(a.items())=> 2017-05-23 13:55:03