2

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?

William Jackson
  • 1,130
  • 10
  • 24
Max Carroll
  • 4,441
  • 2
  • 31
  • 31

3 Answers3

5

You could use a generator:

next(attr for attr in attributes if attr['id'] == id_to_find)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

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'}
Zero
  • 74,117
  • 18
  • 147
  • 154
  • Both soloutions are very good and much better than my own, but John you are in more need of reputation that Daniel, so I chose your answer, also it is very neat, tidy and simple – Max Carroll Apr 07 '15 at 18:52
1

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']
Amrita Sawant
  • 10,403
  • 4
  • 22
  • 26