Python sum values in tuple in a list in a dictionary?

五迷三道 提交于 2019-12-23 02:56:33

问题


In my dictionary, each entry has a list of tuples (my python grammar may be wrong, please bear with me). It looks something like this:

{1: [(2, 2), (4, 3), (6, 1), (7, 1), (8, 3)], 2: [(4, 1), (5, 3), (1, 2)],...}

I'd like to sum the second value in the tuple for each entry, i.e.:

{1: (10), 2: (5)...}

I have been using different forms of

result = sum(y for v in dict.itervalues() for (x, y) in v)

But it adds up all of the values for both entries.


回答1:


You can do something like this:

Edit: Thanks to @ vaultah's comment.

a = {1: [(2, 2), (4, 3), (6, 1), (7, 1), (8, 3)], 2: [(4, 1), (5, 3), (1, 2)]}
final = {k:(sum(j for _,j in v),) for k,v in a.items()}
print(final)

Output:

>>> {1: (10,), 2: (6,)}



回答2:


sum = 0
for item in dict:
    for _,x in dict[item]:
        sum = sum + x
    print sum



回答3:


Another way to solve it using map/lambda:

result = {k: sum(map(lambda x: x[1], v)) for k, v in dict.items()}


来源:https://stackoverflow.com/questions/43400223/python-sum-values-in-tuple-in-a-list-in-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!