繁体   English   中英

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

[英]Return a specific dict from a list of dicts

如果我有以下代码

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

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

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

你可以使用一个发电机:

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

例如,您想要返回'id'='29'

这有效

[x for x in attributes if x['id']=='29'][0]

{'attribute': 's', 'group': 'taille_textile', 'id': '29'}

另一种方法是将List转换为pandas DataFrame。

    import pandas as pd
    df = pd.DataFrame(attributes)

    #get all columns where id=8
    print df[df['id']=='8']

    #get specific column where id=29
    print df['attribute'][df['id']=='29']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM