gpt4 book ai didi

python - 从字典列表中返回一个特定的字典

转载 作者:行者123 更新时间:2023-11-28 20:20:57 25 4
gpt4 key购买 nike

如果我有下面的代码

attributes = []

attributes.append({'attribute': 'noir', 'group': 'coloris', 'id': '8'})
attributes.append({'attribute': 's', 'group': 'taille_textile', 'id': '29'})
attributes.append({'attribute': 'm', 'group': 'taille_textile', 'id': '24'})
attributes.append({'attribute': 'l', 'group': 'taille_textile', 'id': '25'})
attributes.append({'attribute': 'xl', 'group': 'taille_textile', 'id': '26'})

我想返回一个包含特定 id 的列表对象,最好的方法是什么?

我知道一种解决方案是像这样使用 for 循环

def getItemById(id):
for i in attributes:
for k,v in i.items():
if (k == 'id' and v == id):
return i

我敢肯定,除了这个之外,一定有更优雅或更有效的方法吗?

这里有机会使用 lambda 吗?这会带来性能优势吗?

最佳答案

你可以使用生成器:

next(attr for attr in attributes if attr['id'] == id_to_find)

关于python - 从字典列表中返回一个特定的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29497327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com