Python:将两个dicts加在一起

时间:2013-07-24 01:35:34

标签: python

Alrigt,假设我有这两个词典:

A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
B = {(3,'y'):4, (6,'y'):6}

我正在尝试将它们添加到一起,以便我得到类似于此的词典:

C = {(3,'x'):-2,(3,'y'):4, (6,'y'):9, (8, 'b'):9}

我尝试过这样做的理解能够解决任何问题。但对新手来说似乎有点困难。我处在这样的水平,我尝试这样的东西,例如:

编辑:

>>> {k:A[k]+B[d] for k in A for d in B}
{(6, 'y'): 7, (3, 'x'): 2, (8, 'b'): 13}

我得到了这么多,因为它有所帮助,但它遗漏了 (3,'y'):4由于某种原因

7 个答案:

答案 0 :(得分:11)

我会使用collections.Counter

>>> A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
>>> B = {(3,'y'):4, (6,'y'):6}
>>> import collections
>>> C = collections.Counter(A)
>>> C.update(B)
>>> dict(C)
{(3, 'y'): 4, (8, 'b'): 9, (3, 'x'): -2, (6, 'y'): 9}

答案 1 :(得分:7)

由于你使用的是Python 3,一种可能的方法是:

>>> A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
>>> B = {(3,'y'):4, (6,'y'):6}
>>> {k: A.get(k,0) + B.get(k,0) for k in A.keys() | B.keys()}
{(8, 'b'): 9, (3, 'x'): -2, (6, 'y'): 9, (3, 'y'): 4}

在Python 3中,.keys()返回一个dict_keys对象,我们可以使用|运算符来获取两者的并集。 (这就是A.keys() + B.keys()不起作用的原因。)

(我可能会自己使用Counter,FWIW。)

答案 2 :(得分:4)

迭代A和B中的键列表

>>> A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
>>> B = {(3,'y'):4, (6,'y'):6}
>>> C = dict()
>>> for key in set(A.keys() + B.keys()):
...     C[key] = A.get(key, 0) + B.get(key, 0)
... 
>>> C
{(3, 'y'): 4, (8, 'b'): 9, (3, 'x'): -2, (6, 'y'): 9}

答案 3 :(得分:2)

这可能不是最有效的方法,但它更通用。

#!/usr/bin/python
A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
B = {(3,'y'):4, (6,'y'):6}

dd={}
for d in (A, B): #Put as many dictionaries as you would like here
  for key, value in d.iteritems():
    dd[key] = dd.get(key, 0) + value

答案 4 :(得分:1)

我的建议是:

for i in dictA.items():
    if i[0] not in dictA:
        dictB[i[0]] = i[1]
    else:
        dictB[i[0]] = dictB[i[0]] + i[1]

这可能是最不花哨的一个

答案 5 :(得分:1)

这是一个使用理解的解决方案。

A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
B = {(3,'y'):4, (6,'y'):6}

C = {k:A.get(k, 0) + B.get(k, 0) for k in set(A.keys() + B.keys())}

print C
# {(3, 'y'): 4, (8, 'b'): 9, (3, 'x'): -2, (6, 'y'): 9}

这样做是将键组合在一起并删除任何重复项。然后它只是将每个键的值加在一起。如果A或B中没有其中一个值,则只需从另一个dict中获取值。

答案 6 :(得分:1)

#Needed if you're using python3
from functools import reduce    

A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
B = {(3,'y'):4, (6,'y'):6}

#Merging all the key/value(s) inside one big list
C = list(A.items()) + list(B.items())
#C = [((3,'x'), -2), ((6,'y'), 3), ...]    

#Keeping a list of all unique (hence the set) keys available
keys = set([key[0] for key in C])
#keys = set([(3,'x'), (6,'y'), ...])

result = {}
for key in keys:
    #Extracing the pairs that corresponds to the current key
    local = [item for item in C if item[0] == key]
    #local = [((6,'y'), 3), ((6,'y'), 6)]

    #Actually doing the sum and storing the ready to insert result
    my_sum = reduce(lambda x,y: (x[0], x[1] + y[1]), local)
    #my_sum = [((6,'y'), 9)]

    #Actually inserting the result into the result set
    result.update({my_sum[0]: my_sum[1]})
    #result.update({(6,'y'): 9})

>>> result
{(3, 'y'): 4, (8, 'b'): 9, (3, 'x'): -2, (6, 'y'): 9}