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.
解决方案
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,)}