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 08:30:05 EDT 2008


Jon Bowlas wrote:

> Hrmm, any ideas why I'd be getting 'SyntaxError: invalid syntax' for
> both of these?
> 
>> sum(u'Level 2 Courses' in dct for dct in yourlist)
>> q = set(['1']); print q, sum(d.get('level') in q for d in thelist)
> 
> The error occurs at the 'for'

> I'm afraid I can't use Peters suggestion as I'm using python 2.3 and
> it doesn't have the collection module. Thanks anyway.

John's suggestion uses a generator expression (new in 2.4). Try a list
comprehension instead:

q = set(['1']); print q, sum([d.get('level') in q for d in thelist])

You can modify my code to use normal dictionaries:

freq = {}
for course in courses:
    level = course[u"level"]
    freq[level] = freq.get(level, 0) + 1
print freq

Peter



More information about the Python-list mailing list