2012-03-22 42 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