The Python Oracle

Filter items in a dict of dict

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Island

--

Chapters
00:00 Question
00:57 Accepted answer (Score 3)
01:31 Answer 2 (Score 2)
01:48 Answer 3 (Score 1)
02:09 Thank you

--

Full question
https://stackoverflow.com/questions/1939...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 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: []



ANSWER 2

Score 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.




ANSWER 3

Score 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())