How to filter a dictionary according to an arbitrary condition function? How to filter a dictionary according to an arbitrary condition function? python python

How to filter a dictionary according to an arbitrary condition function?


You can use a dict comprehension:

{k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}

And in Python 2, starting from 2.7:

{k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}


dict((k, v) for k, v in points.items() if all(x < 5 for x in v))

You could choose to call .iteritems() instead of .items() if you're in Python 2 and points may have a lot of entries.

all(x < 5 for x in v) may be overkill if you know for sure each point will always be 2D only (in that case you might express the same constraint with an and) but it will work fine;-).


points_small = dict(filter(lambda (a,(b,c)): b<5 and c < 5, points.items()))