简体   繁体   中英

Sum Values Based on Keys in a Separate Python List

I have a dictionary called hits below.

hits = {"The Weeknd": 6, "Maroon 5": 0, "Justin Bieber": 8, "Post Malone": 5}

I also have a separate, standalone list titled artists :

artists = ["The Weeknd", "Justin Bieber"]

I'd like to sum the total values in the hits dictionary based on the keys listed in the artists list (ie, answer would be 6 + 8 = 14).

sum([v for k,v in hits.items() if k in artists ])

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