运行循环以汇总不同字典的元素

时间:2018-05-24 07:31:58

标签: python

我想添加大量字典中存在的类似键值。我在所有字典上运行for循环并更新键值,但不是对键值求和,而是给出了最后一个字典中存在的键值。 例如:如果x,y,z是3个字典,我想使用for循环添加所有字典中存在的类似元素值,因为字典的数量可能很大。

x = {'both1':0, 'both2':2, 'only_x': 100 }
y = {'both1':1, 'both2': -200, 'only_y':203 }
z = {'both1':5, 'both2': 400, 'only_y':13 }

a = {}
for i in x,y,z:
    a.update(i)
print a

输出:

{'only_y': 13, 'both2': 400, 'only_x': 100, 'both1': 5}

预期产出:

{'only_y': 216, 'both2': 202, 'only_x': 100, 'both1': 6}

3 个答案:

答案 0 :(得分:2)

如果您不想使用Counter:

a = {}
for i in [x,y,z]:
    for k,v in i.iteritems():
        if k in a.keys():
            a[k] = a[k] + v
        else:
            a[k] = v

请注意,如果您使用的是python 3.x,则需要使用a.items()而不是a.iteritems()。

答案 1 :(得分:1)

摆脱if .. else ...的另一种方法:

a = {}
for i in x,y,z:
    for k, v in i.iteritems():
        a[k] = a.get(k, 0) + v

答案 2 :(得分:1)

在这种情况下,您可以使用Counter ,以便处理应使用update方法的负值。

来自文档:https://docs.python.org/2/library/collections.html#collections.Counter.update

  

...小数将起作用,支持负值。 update()和subtract()也是如此,它们允许输入和输出的负值和零值。

from collections import Counter

x = {'both1': 0, 'both2': 2, 'only_x': 100}
y = {'both1': 1, 'both2': -200, 'only_y': 203}
z = {'both1': 5, 'both2': 400, 'only_y': 13}

C = Counter(x)
C.update(y)
C.update(z)

# {'only_y': 216, 'both2': 202, 'only_x': 100, 'both1': 6}

您可以通过定义函数

来自动执行此操作
def updateCounter(*args):
    C = Counter()

    for arg in args:
        C.update(arg)
    return C

updateCounter(x, y, z)

# output 
# Counter({'only_y': 216, 'both2': 202, 'only_x': 100, 'both1': 6})