简体   繁体   中英

Return a specific dict from a list of dicts

If I had the following code

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'})

and I wanted to return an object of the list which contained a certain id, what would be the best way to do that?

I know that one solution would be to use the for loop like this

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

I'm sure there must be a much more elegant or efficient way to do it other than this?

Is there an opportunity to use lambdas here? would that give a performance benefit?

你可以使用一个发电机:

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

For example, you want to return object with 'id'='29'

This works

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

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

Another approach is to convert List to a 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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