Reputation: 2825
I have multiple dictionaries nested within a list mydict
and one of the keys 'dummy'
has values 0 or 1, and I want to add all of these values. I indexed the key correctly but I'm not getting the sum, the error reads 'int' object is not iterable
mydict = [{'name':'John', 'dummy': 1},{'name':'Brad','dummy': 0}]
for i in range(len(mydict)):
print sum(mydict[i]['dummy'])
Since my dictionaries are nested, mydict[i]['dummy']
is either 0 or 1, and type(mydict[0]['dummy'])
is an integer.
I'm not sure why then I can't get the sum using the loop above.
Upvotes: 0
Views: 370
Reputation: 1981
sum()
expect an iterable and as you said mydict[0]['dummy']
is an integer.
Try this:
list_of_dicts = [{'name':'John', 'dummy': 1},{'name':'Brad','dummy': 0}]
print sum([element['dummy'] for element in list_of_dicts ] )
This will create a list with the dummy values on the dict and them it will add them.
Upvotes: 2