词典中的词典的Python列表理解? [英] Python list comprehension for dictionaries in dictionaries?

查看:149
本文介绍了词典中的词典的Python列表理解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚了解了列表的理解,这是一个很好的方法来获取一行代码中的数据。但是有一些东西让我失望。

I just learned about list comprehension, which is a great fast way to get data in a single line of code. But something's bugging me.

在我的测试中,我在列表中有这样的字典:

In my test I have this kind of dictionaries inside the list:

[{'y': 72, 'x': 94, 'fname': 'test1420'}, {'y': 72, 'x': 94, 'fname': 'test277'}]

列表理解 s = [r for list in list if r ['x']> 92和r ['x'] < 95和r ['y']> 70和r ['y'] < 75] 完美地工作(事实上,这行的结果)

The list comprehension s = [ r for r in list if r['x'] > 92 and r['x'] < 95 and r['y'] > 70 and r['y'] < 75 ] works perfectly on that (it is, in fact, the result of this line)

无论如何,我意识到我不是真的在我的另一个项目中使用一个列表,我正在使用一个字典。像这样:

Anyway, I then realised I'm not really using a list in my other project, I'm using a dictionary. Like so:

{'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'}}

这样我可以用 var ['test1420'] = ...

但列表推导不行!
我不能以这种方式编辑列表,因为您无法分配这样的索引。

But list comprehensions don't work on that! And I can't edit lists this way because you can't assign an index like that.

有另一种方法吗?

推荐答案

您可以这样做:

s = dict([ (k,r) for k,r in mydict.iteritems() if r['x'] > 92 and r['x'] < 95 and r['y'] > 70 and r['y'] < 75 ])

这需要你指定的dict,并返回一个'过滤'dict。

This takes a dict as you specified and returns a 'filtered' dict.

这篇关于词典中的词典的Python列表理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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