Python列表理解字典中的字典?

发布于 2024-09-08 19:31:36 字数 588 浏览 5 评论 0原文

我刚刚了解了列表理解,这是在一行代码中获取数据的快速方法。但有件事困扰着我。

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

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

列表理解 s = [ r for r in list if r['x'] > 92 且 r['x'] < 95、r['y']>; 70 且 r['y'] < 75] 完美地解决了这个问题(事实上,这是这一行的结果)

无论如何,我后来意识到我并没有真正在我的其他项目中使用列表,我正在使用字典。像这样:

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

这样我就可以简单地使用 var['test1420'] = ... 编辑我的字典,

但是列表推导式对此不起作用! 我无法以这种方式编辑列表,因为您无法分配这样的索引。

还有别的办法吗?

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'}]

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

That way I can simply edit my dictionary with 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.

Is there another way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

你与清晨阳光 2024-09-15 19:31:36

您可以这样做:

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

这需要您指定的字典并返回“过滤”字典。

You can do this:

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

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

萌辣 2024-09-15 19:31:36

如果 dct 是

{'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'},
 'test277': {'y': 72, 'x': 94, 'fname': 'test277'},}

也许你正在寻找类似的东西:

[ subdct for key,subdct in dct.iteritems() 
  if 92<subdct['x']<95 and 70<subdct['y']<75 ]

一点好处是 Python 允许你链接不等式:

92<dct[key]['x']<95

而不是

if r['x'] > 92 and r['x'] < 95

注意上面我已经写了一个列表理解,所以你会得到一个列表(在这种情况下,是字典)。

在 Python3 中,还有诸如 dict 推导式之类的东西:

{ n: n*n for n in range(5) } # dict comprehension
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

在 Python2 中,相当于

dict( (n,n*n) for n in range(5) )

I我不确定您是否正在寻找字典列表或字典的字典,但如果您理解上面的示例,则很容易修改我的答案以获得您想要的内容。

If dct is

{'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'},
 'test277': {'y': 72, 'x': 94, 'fname': 'test277'},}

Perhaps you are looking for something like:

[ subdct for key,subdct in dct.iteritems() 
  if 92<subdct['x']<95 and 70<subdct['y']<75 ]

A little nicety is that Python allows you to chain inequalities:

92<dct[key]['x']<95

instead of

if r['x'] > 92 and r['x'] < 95

Note also that above I've written a list comprehension, so you get back a list (in this case, of dicts).

In Python3 there are such things as dict comprehensions as well:

{ n: n*n for n in range(5) } # dict comprehension
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

In Python2 the equivalent would be

dict( (n,n*n) for n in range(5) )

I'm not sure if you are looking for a list of dicts or a dict of dicts, but if you understand the examples above, it is easy to modify my answer to get what you want.

暖伴 2024-09-15 19:31:36

听起来你想要类似的东西:

my_dict = {'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'},
           'test277' : {'y': '072', 'x': '094', 'fname': 'test277'}}


new_dict = dict((k,v) for k,v in my_dict.items() 
                    if 92 < int(v['x']) < 95 and 70 < int(v['y']) < 75)

关于此代码的一些注释:

  1. 我正在使用生成器表达式
    而不是列表推导式
  2. Python 可以让你组合不等式,
    测试为 low <值< high
  3. dict() 构造函数接受一个可迭代对象
    键/值元组来创建
    字典

Sounds like you want something like:

my_dict = {'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'},
           'test277' : {'y': '072', 'x': '094', 'fname': 'test277'}}


new_dict = dict((k,v) for k,v in my_dict.items() 
                    if 92 < int(v['x']) < 95 and 70 < int(v['y']) < 75)

Some notes on this code:

  1. I'm using a generator expression
    instead of a list comprehension
  2. Python lets you combine inequality
    tests as low < value < high
  3. The dict() constructor takes an iterable
    of key/value tuples to create a
    dictionary
凉栀 2024-09-15 19:31:36

在 Python 3 中,您可以使用字典理解,这可能是一个更短的解决方案:

{key_expression(item) : value_expression(item) for item in something if condition}
  1. 如果您想像原始问题一样过滤字典:

    mydict = {'test1': {'y': 60},'test2': {'y': 70},'test3': {'y': 80}}
    s = {k : r for k,r in mydict.items() if r['y'] < 75}
    > {'test1': {'y': 60}, 'test2': {'y': 70}}
    
  2. 或者我们甚至可以在列表或范围之外创建一些内容。例如,如果我们想要一个包含所有奇数平方数的字典:

    {i : i**2 for i in range(11) if i % 2 == 1}
    > {1:1、3:9、5:25、7:49、9:81}
    

In Python 3 you can use dict comprehension which can be an even shorter solution:

{key_expression(item) : value_expression(item) for item in something if condition}
  1. In case you want to filter a dictionary as in the original question:

    mydict = {'test1': {'y':  60},'test2': {'y':  70},'test3': {'y':  80}}
    s = {k : r for k,r in mydict.items() if r['y'] < 75 }
    > {'test1': {'y': 60}, 'test2': {'y': 70}}
    
  2. Or we can even create something out of a list or range. E.g. if we want a dictionary with all odd square numbers:

    {i : i**2 for i in range(11) if i % 2 == 1}
    > {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
    
你的笑 2024-09-15 19:31:36

您可以使用 d.values() 获取字典 d 的值列表。你的列表理解应该使用它来工作,尽管我有点不清楚你到底想要输出是什么。

You can get a list of the values of a dictionary d with d.values(). Your list comprehension should work using that, although I'm a little unclear what exactly you want the output to be.

長街聽風 2024-09-15 19:31:36

还有别的办法吗?

为什么不考虑使用一些轻量级的对象呢?

您仍然可以使用列表推导式来收集或过滤对象,并在清晰度/可扩展性方面获得很大的提升。

>>> class Item(object):
...     def __init__(self, x, y, name):
...         self.x = x
...         self.y = y
...         self.name = name
... 
>>> list_items = []
>>> list_items.append(Item(x=70, y=60, name='test1420'))                        
>>> list_items.append(Item(x=94, y=72, name='test277'))                         
>>> items_matching = [item for item in list_items 
                      if 92 < item.x < 95 and 70 < item.y < 75]
>>> for item in items_matching:
...     print item.name
... 
test277
>>> first_item = items_matching[0]
>>> first_item.x += 50
>>> first_item.x
144

Is there another way?

Why not consider the use of some lightweight objects?

You can still use list comprehensions for gathering or filtering the objects, and gain a lot in clarity / extensibility.

>>> class Item(object):
...     def __init__(self, x, y, name):
...         self.x = x
...         self.y = y
...         self.name = name
... 
>>> list_items = []
>>> list_items.append(Item(x=70, y=60, name='test1420'))                        
>>> list_items.append(Item(x=94, y=72, name='test277'))                         
>>> items_matching = [item for item in list_items 
                      if 92 < item.x < 95 and 70 < item.y < 75]
>>> for item in items_matching:
...     print item.name
... 
test277
>>> first_item = items_matching[0]
>>> first_item.x += 50
>>> first_item.x
144
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文