Python 在具有显式键值的对象列表中查找元素

Python 在具有显式键值的对象列表中查找元素,python,python-2.7,types,Python,Python 2.7,Types,我有一个python中的对象列表: accounts = [ { 'id': 1, 'title': 'Example Account 1' }, { 'id': 2, 'title': 'Gow to get this one?' }, { 'id': 3, 'title': 'Example Account 3' }, ] 我需要获取id为2的对象

我有一个python中的对象列表:

accounts = [
    {
        'id': 1,
        'title': 'Example Account 1'
    },
    {
        'id': 2,
        'title': 'Gow to get this one?'
    },
    {
        'id': 3,
        'title': 'Example Account 3'
    },
]
我需要获取id为2的对象


当我只知道对象属性的值时,如何从该列表中选择合适的对象?

给定您的数据结构:

>>> [item for item in accounts if item.get('id')==2]
[{'title': 'Gow to get this one?', 'id': 2}]
如果项目不存在:

>>> [item for item in accounts if item.get('id')==10]
[]
也就是说,如果您有机会这样做,您可能会重新考虑您的数据结构:

accounts = {
    1: {
        'title': 'Example Account 1'
    },
    2: {
        'title': 'Gow to get this one?'
    },
    3: {
        'title': 'Example Account 3'
    }
}
然后,您可以通过索引数据的id或使用直接访问数据,具体取决于您希望如何处理不存在的密钥

>>> 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

这将返回列表中id==2的任何元素

limited_list = [element for element in accounts if element['id'] == 2]
>>> limited_list
[{'id': 2, 'title': 'Gow to get this one?'}]

这似乎是一个奇怪的数据结构,但可以做到:

acc = [account for account in accounts if account['id'] == 2][0]
也许使用id号作为键的字典更合适,因为这使访问更容易:

account_dict = {account['id']: account for account in accounts}
如果某个dict不包含键,则最好使用if item.get'id'==2的可能副本