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

counting specific dictionary entries in python

I have a python dictionary and I want to count the amount of keys that have a specific format.
The keys that I want to count are all the keys that have the format ‘letter, number, number’.
In my specific case the key always begins with the letter ‘A’. only the numbers change.
Example: A12, A16, A71

For example I want to count all the entries that have this AXX format (where the X’s are numbers).

{'A34': 83, 'B32': 70, 'A44': 66, A12: 47, 'B90': 71}

I know I can count all the entries of my dictionary by using:

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

print(len(my_dict.keys()))

but how do I count up all the entries that have the specific format I need.

>Solution :

You can use a generator comprehension inside the sum function:

print(sum(1 for k in d.keys() if k.startswith('A') and len(k) == 3 and k[1:3].isdigit()))

This does three checks: if the key starts with A, if the length of this key is 3 and if the last two characters of this key is a digit.

You can also use Regex:

import re
print(sum(1 for k in d.keys() if re.match('^A\\d{2}$', k)))

Both snippets outputs 3.

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