如何根据任意条件函数过滤字典? [英] How to filter a dictionary according to an arbitrary condition function?

查看:132
本文介绍了如何根据任意条件函数过滤字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分数字典,例如:

I have a dictionary of points, say:

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

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

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'.

根据这本书,每个字典都有 items()函数,它返回一个(键,对) tuple:

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

所以我写了:

>>> 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) function ...

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

推荐答案

现在,在Python 2.7及以上版本中,您可以使用一个字母理解:

Nowadays, in Python 2.7 and up, you can use a dict comprehension:

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

而在Python 3中:

And in Python 3:

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

这篇关于如何根据任意条件函数过滤字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆