Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

summing up key value pairs in python dictionary

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading