Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum the nth value for every key in a python dictionary

EDIT

I have the following dictionary:

dictionary = {'abc': [20, 'john'], 'def': [25, 'jim'], 'ghi': [30, 'jack']}

I would like to sum all of the first values for each key and define it as a variable

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected answer:

20 + 25 + 30

total_score = 75

>Solution :

You have a dict() having set() assigned to each key. You can not index sets. So considering that the first value in the set will always be the value you want is meaningless.

A workaround is to use list comprehension to build a list() from the set(), that list containing only integer elements. Since you only have one integer per set, then the first index of the list will be the value of interest.

dct = {'abc': {20, 'john'}, 'def': {25, 'jim'}, 'ghi': {30, 'jack'}}

var = 0

for v in dct.values():
    v = [x for x in v if isinstance(x, int)][0]
    var += v
    
print(var)

Output:

75

Edit:

Since the OP edited his question, the new code would be:

dct = {'abc': [20, 'john'], 'def': [25, 'jim'], 'ghi': [30, 'jack']}

var = 0

for v in dct.values():
    var += v[0]
    
print(var)

Or:

var = sum(v[0] for v in dct.values())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading