The Python Oracle

Filter items in a dict of dict

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping

--

Chapters
00:00 Filter Items In A Dict Of Dict
00:38 Answer 1 Score 2
00:52 Accepted Answer Score 3
01:17 Answer 3 Score 1
01:28 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())