Python:根据dict中的内容从列表中获取一个dict [英] Python: get a dict from a list based on something inside the dict
问题描述
我需要能够在列表中找到一个项目
(这个例子中的一个项目是 dict
)基于 dict
内的一些值。 列表的结构
我需要处理如下:
[
{
'title':'some value',
'value':123.4,
'id':'an id'
},
{
'title':'another title',
'value':567.8,
'id':'another id'
},
{
'title':'last title',
'value':901.2,
'id':'另一个id'
}
]
注意事项: 标题
和 value
可以是任何值(和相同), id
将是唯一的。
我需要能够从这个列表
中获得 dict
,基于唯一的 ID
。我知道这可以通过使用循环来完成,但这似乎很麻烦,我有一种感觉,这是一个明显的方法,我没有看到感谢大脑融化。
my_item = next((item for item in my_list if item ['id'] == my_unique_id),None)
这将遍历列表,直到找到与 my_unique_id
,然后停止。它不会在内存中存储任何中间列表(通过使用生成器表达式)或需要显式循环。它将 my_item
设置为没有找到没有对象的
。它与my_list中的项目的
$ b大致相同:
如果项目['id'] == my_unique_id:
my_item = item
break
else:
my_item =无
c
I need to be able to find an item in a list
(an item in this case being a dict
) based on some value inside that dict
. The structure of the list
I need to process looks like this:
[
{
'title': 'some value',
'value': 123.4,
'id': 'an id'
},
{
'title': 'another title',
'value': 567.8,
'id': 'another id'
},
{
'title': 'last title',
'value': 901.2,
'id': 'yet another id'
}
]
Caveats: title
and value
can be any value (and the same), id
would be unique.
I need to be able to get a dict
from this list
based on a unique id
. I know this can be done through the use of loops, but this seems cumbersome, and I have a feeling that there's an obvious method of doing this that I'm not seeing thanks to brain melt.
my_item = next((item for item in my_list if item['id'] == my_unique_id), None)
This iterates through the list until it finds the first item matching my_unique_id
, then stops. It doesn't store any intermediate lists in memory (by using a generator expression) or require an explicit loop. It sets my_item
to None
of no object is found. It's approximately the same as
for item in my_list:
if item['id'] == my_unique_id:
my_item = item
break
else:
my_item = None
else
clauses on for
loops are used when the loop is not ended by a break
statement.
这篇关于Python:根据dict中的内容从列表中获取一个dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!