22

I need to load a list of database row objects into memory, and then grab one of those rows by its unique ID. Is there a clean, pythonic way of finding an single object from a list by an attribute value? Or do I just loop and compare?

Yarin
  • 159,198
  • 144
  • 384
  • 498

3 Answers3

21

Yes, you loop and compare:

items = [item for item in container if item.attribute == value]

And you get back a list which can be tested to see how many you found.

If you will be doing this a lot, consider using a dictionary, where the key is the attribute you're interested in.

kindall
  • 168,929
  • 32
  • 262
  • 294
18

If you do this it only gives the very first match, instead of comparing the whole list: find first sequence item that matches a criterion.

If you do something like this, you don't have to catch the exception but get None instead:

item = next((i for i in items if i == 'value'), None)
Community
  • 1
  • 1
Ruud Althuizen
  • 540
  • 4
  • 10
6

You can filter:

matches = filter(lambda obj: obj.attribute == "target value", myListOfObjects)

Refer to kindall's answer for advice on efficiency. If you're doing this a lot, it's not the right way.

Chris Cooper
  • 16,826
  • 9
  • 51
  • 70