我有一个点的字典,比如说:

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

我想用x和y值小于5的所有点创建一个新字典,即点'a', 'b'和'd'。

根据这本书,每个字典都有items()函数,它返回一个(key, pair)元组列表:

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

所以我这样写:

>>> 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)}

还有更优雅的方式吗?我期待Python有一些超级棒的dictionary.filter(f)函数…


当前回答

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

其他回答

points_small = dict(filter(lambda (a,(b,c)): b<5 and c < 5, points.items()))
dict((k, v) for (k, v) in points.iteritems() if v[0] < 5 and v[1] < 5)
>>> 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.iteritems() if v[0] < 5 and v[1] < 5)

你可以使用字典理解:

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

在Python 2中,从2.7开始:

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