Take the 2-minute tour ×
huge =  sum([x for key in G for (_,x) in G[key]]+1)

This is what I have so far, though its returning a type error, can only concatenate list (not "int") to list which I don't understand.

Basically Im dealing with a data structure something like

{1: [("A",2), ("B",3)]}

and so on like that, so that every key in the dictionary has a value which is a list of tuples, and the second item, index = 1 of each tuple are the values I want to sum, so in the example I gave:

huge = 5   # i.e. 2 + 3

Any advice??

share|improve this question
Recommend you add a line of code that provides the input. –  Mr E Feb 15 '12 at 12:29
Looks good, just remove the +1. Alternatively: sum(v[1] for l in G.itervalues() for v in l). –  Felix Kling Feb 15 '12 at 12:29

7 Answers 7

up vote 4 down vote accepted
>>> G = {1:[("A",2),("B",3)]}
>>> sum(y for v in G.itervalues() for (x, y) in v)

The errors comes from the expression [x for key in G for (_,x) in G[key]] + 1 which is trying to add a list and a number. That's a TypeError.

share|improve this answer

I think what you're looking for is something like this:

for itertools import chain
sum([v for _, v in chain.from_iterable(G.values())])

or with lazy evaluation:

sum(v for _, v in chain.from_iterable(G.itervalues()))
share|improve this answer

My python's rusty, but you have essentially

huge = sum([...list...] + 1)

I think it's complaining that you're adding 1 to a list. Did you mean:

huge = sum([...list...]) + 1
share|improve this answer
sum = 0
for key, item in data.iteritems():
    for group in item:
        sum += group[-1]

Should work just fine.

NOT everything has to be a list comprehension

share|improve this answer

I think we didn't have yet

sum(group[1] for value in data.itervalues() for group in value)


share|improve this answer

This may not be the most Pythonic, but it is straight-forward:

my_map = {1:[("A",1),("B",2)],2:[("C",3),("D",4)]}

total = 0

for k in my_map.keys():
    this_list = my_map[k]
    for this_tuple in this_list:
        total += this_tuple[1]

print total
share|improve this answer
Unfortunate variable name choices, ISTM. This clobbers three builtins: map, list, and tuple. –  DSM Feb 15 '12 at 12:58
Good point. I have edited. The new names aren't great but will serve the example, IMO. –  Michael Easter Feb 15 '12 at 13:06

Are you saying you only want to sum up the tuples in the list G[1]? If so, this is what you were after:

huge = sum(x for _, x in G[1])

Note: You don't need to build a new list before summing it; leaving out the square brackets does it in one pass.

share|improve this answer

Your Answer


