Home > Mobile >  Sum Values Based on Keys in a Separate Python List
Sum Values Based on Keys in a Separate Python List

Time:06-19

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).

CodePudding user response:

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

  • Related