How to filter a dictionary according to an arbitrary condition function?
points_small = dict(filter(lambda (a,(b,c)): b<5 and c < 5, points.items()))
>>> points = {'a': (3, 4), 'c': (5, 5), 'b': (1, 2), 'd': (3, 3)}
>>> dict(filter(lambda x: (x[1][0], x[1][1]) < (5, 5), points.items()))
{'a': (3, 4), 'b': (1, 2), 'd': (3, 3)}
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;-).
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}