Count number of keys in ordered dict that start with specific string

128 Views Asked by At

I'd like to count the number of strings in an ordered dict that start with a particular string. For example, I have the following ordered dict:

OrderedDict([('Name', 'First'), ('Size': '10'), ('Rate 1', '1000'), ('Rate 2', '100'), ('End', 'Last'])

I want to count the number of keys that start with "Rate". In this example, it would be 2.

I tried n = len(o_dict.keys().startswith('Rate')) with but this results in AttributeError: 'odict_keys' object has no attribute 'startswith'.

Any idea what to do here? Thanks in advance.

1

There are 1 best solutions below

0
On
from collections import OrderedDict

od = OrderedDict([('Name', 'First'), ('Size', '10'), ('Rate 1', '1000'), ('Rate 2', '100'), ('End', 'Last')])
cnt = sum([1 for key in od.keys() if key.startswith("Rate")])
print(cnt)

Output

2