Home > OS >  Returning sum of first value in a Python Dictionary
Returning sum of first value in a Python Dictionary

Time:06-04

Hi I have a dictionary where I want to return the sum of the first value for each key

mydict= {'buddy': [9, 14, 'dog'],
             'snowball': [3, 10, 'cat'],
             'bella': [5, 3, 'dog'],
             'polly': [2, 3, 'bird']}

So I want the sum of the first value so sum should equal 19 Any help would be really appreciated!

CodePudding user response:

You can use sum() in conjunction with a generator like this:

mydict= {'buddy': [9, 14, 'dog'],
             'snowball': [3, 10, 'cat'],
             'bella': [5, 3, 'dog'],
             'polly': [2, 3, 'bird']}

print(sum(x[0] for x in mydict.values()))

Output:

19

CodePudding user response:

May be this could help you.But most efficient solution is of @Albert Winestein

Code :

mydict= {'buddy': [9, 14, 'dog'],'snowball': [3, 10, 'cat'],'bella': [5, 3, 'dog'],'polly': [2, 3, 'bird']}
   
print(sum([i[1][0] for i in mydict.items() ]))

CodePudding user response:

As you want the first item, here is an approach using zip to transpose the values and next to get the first items:

sum(next(zip(*mydict.values())))

Output: 19

  • Related