Help counting the total number of dictionaries inside a list that contain a specified key value

Peter Otten __peter__ at web.de
Tue Aug 12 07:34:40 EDT 2008


Jon Bowlas wrote:

> I have the following list containing dictionaries and I would like to
> be able to count the total number of dictionaries I have that contain
> a certain value set for the 'level' key:

> For example I'd like to kow how many dictionaries there are with a
> level 1, 2 , 23 & 3 etc. How would one go about achieveing this?

from collections import defaultdict
freq = defaultdict(int)
for course in courses:
    freq[course[u"level"]] += 1
print freq

Peter



More information about the Python-list mailing list