简体   繁体   中英

how to get the sum of python dictionary listed as a tuple?

I have python dictionary listed as tuples as follows; Here the first value of the each tuple depicts the group number and each dictionary depicts the generated value related to the each number inside the group, (ie, {'1': 0,'3': 1,'2': 1,'5': 2,'303': 3}.

[('1',{'1': 0,'3': 1,'2': 1,'5': 2,'303': 3}), ('2',{'4': 0,'5': 1,'7': 1,'5': 2,'303': 2}), ('3',{'1': 0,'3': 0,'2': 0,'5': 2,'303': 3})]

Is there any method to get the sum of the each group by getting the sum of the each group, (ie,

[('1', 7), ('2', 6), ('3', 5)]

I tried to iterate over the each value and get the sum but that method is so expensive.

A simple list comprehension should so

>>> [(k, sum(dic.values())) for k, dic in tuples]
lst = [ ("1", {"1": 0, "3": 1, "2": 1, "5": 2, "303": 3}), ("2", {"4": 0, "3": 1, "7": 1, "5": 2, "303": 2}), ("3", {"1": 0, "3": 0, "2": 0, "5": 2, "303": 3}), ] sum_of_each_group = [(i, sum(d.values())) for (i, d) in lst] print(sum_of_each_group) # output: [('1', 7), ('2', 6), ('3', 5)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM