Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element in list of objects with explicit key value

I have a list of objects in python:

accounts = [
    {
        'id': 1,
        'title': 'Example Account 1'
    },
    {
        'id': 2,
        'title': 'Gow to get this one?'
    },
    {
        'id': 3,
        'title': 'Example Account 3'
    },
]

I need to get object with id=2.

How can I select a proper object from this list, when I know only the value of the object attributes?

like image 400
dease Avatar asked Aug 27 '14 13:08

dease


People also ask

How do I find a specific element 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 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 .


2 Answers

Given your data structure:

>>> [item for item in accounts if item.get('id')==2]
[{'title': 'Gow to get this one?', 'id': 2}]

If item does not exist:

>>> [item for item in accounts if item.get('id')==10]
[]

That being said, if you have opportunity to do so, you might rethink your datastucture:

accounts = {
    1: {
        'title': 'Example Account 1'
    },
    2: {
        'title': 'Gow to get this one?'
    },
    3: {
        'title': 'Example Account 3'
    }
}

You might then be able to access you data directly by indexing their id or using get() depending how you want to deal with non-existent keys.

>>> accounts[2]
{'title': 'Gow to get this one?'}

>>> accounts[10]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 10

>>> accounts.get(2)
{'title': 'Gow to get this one?'}
>>> accounts.get(10)
# None
like image 126
Sylvain Leroux Avatar answered Sep 18 '22 18:09

Sylvain Leroux


This will return any element from the list that has an id == 2

limited_list = [element for element in accounts if element['id'] == 2]
>>> limited_list
[{'id': 2, 'title': 'Gow to get this one?'}]
like image 21
bpgergo Avatar answered Sep 19 '22 18:09

bpgergo