从一系列词典中返回一个特定的词典

Max*_*oll 2 python lambda dictionary list object

如果我有以下代码

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'})
Run Code Online (Sandbox Code Playgroud)

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

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

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

我敢肯定除此之外必须有更优雅或更有效的方法吗?

这里有机会使用lambdas吗?这会带来性能上的好处吗?

Dan*_*man 5

你可以使用一个发电机:

next(attr for attr in attributes if attr['id'] == id_to_find)
Run Code Online (Sandbox Code Playgroud)