How to count the number of keys where the values meet a criteria in a list of dictionaries?

Question:

I have a list of dictionaries (see below), and I would count the number of keys, whose values meet a specfic criteria. In this instance, I want to know the number of ‘duration’ keys, whose values are greater than 500.

{'test': [{'duration': 0,
   'is_correct': True},
  {'duration': 518,
   'is_correct': False},
  {'duration': 500,
   'is_correct': False},
  {'duration': 285,
   'is_correct': True,
  {'duration': 300,
   'is_correct': True}]}
Asked By: sos.cott

||

Answers:

Simple list comprehension would do:

d = {'test': [{'duration': 0,
   'is_correct': True},
  {'duration': 518,
   'is_correct': False},
  {'duration': 500,
   'is_correct': False},
  {'duration': 285,
   'is_correct': True},
  {'duration': 300,
   'is_correct': True}]}
len([i for i in d['test'] if i['duration']>500]) 

Or you could use pandas:

import pandas as pd

df = pd.DataFrame(d['test'])
len(df[df['duration']>500])
Answered By: RJ Adriaansen
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.