views:

190

answers:

4

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

A: 
dict((k, v) for (k, v) in points.iteritems() if v[0] < 5 and v[1] < 5)
Ignacio Vazquez-Abrams
you forgot () after iteritems
KillianDS
You need to **call** the method, not just **mention** it: put `()` after the method name `iteritems`.
Alex Martelli
Whoops. Fixed​.
Ignacio Vazquez-Abrams
+2  A: 
dict((k, v) for (k, v) in points.iteritems() if v[0] < 5 and v[1] < 5)
nosklo
A: 
points_small = dict(filter(lambda (a,(b,c)): b<5 and c < 5, points.items()))
sizzzzlerz
+8  A: 
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;-).

Alex Martelli