Home > Back-end >  summing up key value pairs in python dictionary
summing up key value pairs in python dictionary

Time:11-11

I am iterating through a dict and counting up the number of items that are of a certain format in the dict.

sum(1 for key in mydict.keys() if re.match('^D\\d{2}$',key))

I am trying to change it so that I can add up the combined sum of the values who’s keys match my regex format. So instead of ‘1’ being added for each key that matches my format I want to the value of each matching key.

I was trying something like below but I get an error saying: unsupported operand type(s) for : 'int' and 'dict_values'

sum(mydict.values() for key in mydict.keys() if re.match('^D\\d{2}$',key))

CodePudding user response:

Iterate over the keys and values via items and you can sum the values:

sum(v for k, v in mydict.items() if re.match('^D\\d{2}$', k))

Note that I'm assuming the values in mydict are numeric -- if not, you'll want to sum int(v) (or maybe float(v)) instead of just v.

  • Related