HelpMeCode
HelpMeCode

Reputation: 309

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 (i.e., answer would be 6 + 8 = 14).

Upvotes: 1

Views: 46

Answers (1)

Thomas Hilger
Thomas Hilger

Reputation: 476

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

Upvotes: 1

Related Questions