3

Is there a way to return a list of keys whose inner dict's values match certain criteria

given a python dict:

adict = {
    1: {'process':False, 'length':10},
    2: {'process':True, 'length':34},
    ...,
    n: {'process': False, 'length: -3'}
}

Is there a way I can get a list of keys [1, 2, 6...] who's inner dict fit the criteria I want?

def somefiltering(critieria1, critieria2, critieria3...):
    # for variable number of critieria
    # logic
    return list of keys

I know I can simply "loop" through my dictionary, but is there a better way? And also

How do I format somefiltering and format criteria1 to make it work?
simply entering criteria1 = "process = True", won't work?

Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
user1639926
  • 852
  • 2
  • 11
  • 21

3 Answers3

3

Here's a way to do it:

adict = {1: {'process':False, 'length':10}, 2: {'process':True, 'length':34}, 3:{'process': False, 'length': -3}}

def somefiltering(filterDict, *criteria):
    return [key for key in filterDict if all(criterion(filterDict[key]) for criterion in criteria)]

Note that your somefiltering function will need to have the dictionary as an argument.

Example usage:

somefiltering(adict, lambda d:d['process'], lambda d:d['length']>5)
# Result: [2]

somefiltering(adict, lambda d:d['length'] < 20)
# Result: [1, 3]

somefiltering(adict, lambda d:d['process'], lambda d:d['length']<5)
# Result: []
Brionius
  • 13,858
  • 3
  • 38
  • 49
2

If you need list of keys, it's gonna be

[k for k,v in adict.items() if creterion(v)]

And use dict.iteritems() for 2.x.

khachik
  • 28,112
  • 9
  • 59
  • 94
1

Given a list of callables named criteria, the following filter expression will list only the dict keys whose corresponding values meet all the criteria.

filter(lambda key: all(crit(adict[key]) for crit in criteria), adict.keys())
kojiro
  • 74,557
  • 19
  • 143
  • 201