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