简体   繁体   中英

Find the sum of certain values in dictionary

Given a dictionary and an int value p , I want to return the sum of its values where the key is greater than p .

For example:

{5:3,10:5,15:7,20:9} , when p = 18 the result is 9

{20:3,40:5,60:7,80:9} , when p = 25 the result is 5 + 7 + 9 = 21

{10:1,20:2,30:3,40:4} , when p = 29 the result is 3 + 4 =7

What should I do to identify the integer key and sum up the value keys and return an answer?

What about:

>>> d = {5:3,10:5,15:7,20:9}
>>> sum(v for k, v in d.items() if k > 18)
9
>>> d = {20:3,40:5,60:7,80:9}
>>> sum(v for k, v in d.items() if k > 25)
21
>>> d = {10:1,20:2,30:3,40:4}
>>> sum(v for k, v in d.items() if k > 29)
7

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