Python: Filter a dictionary

Posted by Adam Matan on Stack Overflow See other posts from Stack Overflow or by Adam Matan
Published on 2010-05-16T16:30:34Z Indexed on 2010/05/16 16:40 UTC
Read the original article Hit count: 364

Filed under:
|
|

Hi,

I have a dictionary of points, say:

>>> points={'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)}

I want to create a new dictionary with all the points whose x and y value is smaller than 5, i.e. points 'a', 'b' and 'd'.

According to the the book, each dictionary has the items() function, which returns a list of (key, pair) tuple:

>>> points.items()
[('a', (3, 4)), ('c', (5, 5)), ('b', (1, 2)), ('d', (3, 3))]

So I have written this:

>>> for item in [i for i in points.items() if i[1][0]<5 and i[1][1]<5]:
...     points_small[item[0]]=item[1]
...
>>> points_small
{'a': (3, 4), 'b': (1, 2), 'd': (3, 3)}

Is there a more elegant way? I was expecting Python to have some super-awesome dictionary.filter(f) function...

Adam

© Stack Overflow or respective owner

Related posts about python

Related posts about dictionary