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?
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.
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 .
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
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?'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With