如何根据任意条件函数过滤字典?

发布于 2021-02-02 23:13:16

我有一个要点词典,说:

>>> 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)功能…

关注者
0
被浏览
67
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    如今,在Python 2.7及更高版本中,你可以使用dict理解:

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

    在Python 3中:

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看