2017-04-04 67 views
0

喜歡的東西語句[4]是想我......python:如何將collections.defaultdict(int)添加到另一個?

(獲得的,笨拙地&不很理想,通過報表[5] [6])

In [1]: from collections import defaultdict 

In [2]: d1 = defaultdict(int, dict(a=1, b=2, c=3)) 

In [3]: d2 = defaultdict(int, dict(a=10, c=30, d=40)) 

In [4]: d1 |= d2 
TypeError: unsupported operand type(s) for |=: 'collections.defaultdict' and 'collections.defaultdict' 

In [5]: def default_dict_add(d1, key, val): 
      d1[key] += val 

In [6]: [default_dict_add(d1, k, d2[k]) for k in d2.keys()] 
Out[6]: 
[None, None, None] 

In [7]: d1 
defaultdict(int, {'a': 11, 'b': 2, 'c': 33, 'd': 40}) 

類似於你可以用套做(聲明#[44]

In [42]: s1 = {1, 2, 3} 
s1 = {1, 2, 3} 

In [43]: s2 = {10, 30, 40} 
s2 = {10, 30, 40} 

In [44]: s1 |= s2 

In [45]: s1 

Out[45]: 
{1, 2, 3, 10, 30, 40} 

回答

0

好像你正在做的事情會更適合於Counter,這是相同的模塊defaultdict英寸

d1 = Counter(dict(a=1, b=2, c=3)) 
d2 = Counter(dict(a=10, c=30, d=40)) 
d1 + d2 
# Counter({'d': 40, 'c': 33, 'a': 11, 'b': 2}) 
+1

您還可以,如果你想修改'd1'在你的例子使用'D1 + = d2'。 –

+0

真棒 - 謝謝。 –

0

您可以使用Counter

>>> from collections import Counter 
>>> c1 = Counter(d1) 
>>> c2 = Counter(d2) 
>>> c1 + c2 
Counter({'d': 40, 'c': 33, 'a': 11, 'b': 2}) 

或者:

>>> {k: d1.get(k, 0) + d2.get(k, 0) for k in set(list(d1.keys()) + list(d2.keys()))} 
{'a': 11, 'c': 33, 'b': 2, 'd': 40}