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?
Asked
Active
Viewed 3.1k times
3 Answers
23
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
- 178,883
- 35
- 278
- 309
19
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
- 558
- 4
- 10
7
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
- 17,276
- 9
- 52
- 70