jms
jms

Reputation: 43

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

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.

Upvotes: -1

Views: 240

Answers (1)

Andreas
Andreas

Reputation: 159

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

Upvotes: 0

Related Questions