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

John Machin sjmachin at lexicon.net
Tue Aug 12 07:50:26 EDT 2008


On Aug 12, 9:09 pm, "Jon Bowlas" <m... at jonbowlas.com> wrote:
> Hi All,
>
> 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:
>
>
[snip]
>
> 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?
>

Assuming:
   thelist = [etc etc etc]

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

produces:
set(['1']) 1
set(['23']) 3
set(['2', '23']) 7

Is that what you wanted? If you are sure that each dict will have a
'level' key, you can use d['level'] instead of d.get('level').

Cheers,
John



More information about the Python-list mailing list