簡體   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