15

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?

dease
  • 2,685
  • 13
  • 35
  • 66
  • 2
    possible duplicate of [Find object in list that has attribute equal to some value (that meets any condition)](http://stackoverflow.com/questions/7125467/find-object-in-list-that-has-attribute-equal-to-some-value-that-meets-any-condi) – Emil Vikström Aug 27 '14 at 13:17

3 Answers3

24

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
Chris Maes
  • 30,644
  • 6
  • 98
  • 124
Sylvain Leroux
  • 47,741
  • 6
  • 96
  • 115
  • 1
    might be better to use `if item.get('id') == 2` in case some dict does not contain the key – Padraic Cunningham Aug 27 '14 at 13:18
  • as for why the data structure, I can say that I've simply been HANDED such a structure that needs ETL work... wasn't really optional that it was a [{...},{...}] format... just had to find if a key was present in any of said objects to solve a particular need. – Joshua Eric Turcotte Oct 30 '21 at 00:28
1

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?'}]
bpgergo
  • 15,165
  • 3
  • 39
  • 64
0

It seems to be a weird data structure, but it can be done:

acc = [account for account in accounts if account['id'] == 2][0]

Maybe a dictionary with the id-number as key is more appropriate, as this makes the accessing easier:

account_dict = {account['id']: account for account in accounts}
Nras
  • 4,141
  • 2
  • 22
  • 36