23

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?

1
  • 3
    Is there a reason to not doing this directly with a database query? Commented Feb 1, 2012 at 0:45

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

22

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)

Comments

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.

1 Comment

what would be the right way to do so efficiently? Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.