Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list item by attribute in Python

Tags:

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?

like image 396
Yarin Avatar asked Feb 01 '12 00:02

Yarin


People also ask

How do you find a specific object in a list Python?

To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.

How do I get attributes in Python?

Python getattr() function. Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function.

How do you sort a list of objects based on an attribute of the objects?

sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse. The key argument specifies a single-arg function to extract a comparison key from each list object.

How do you filter a list of objects in Python?

Python has a built-in function called filter() that allows you to filter a list (or a tuple) in a more beautiful way. The filter() function iterates over the elements of the list and applies the fn() function to each element. It returns an iterator for the elements where the fn() returns True .


1 Answers

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.

like image 130
kindall Avatar answered Oct 02 '22 17:10

kindall