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

2024-06-10 10:08:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我需要得到id=2的对象。

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


Tags: to对象id列表get属性titleexample
3条回答

这将返回列表中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}

鉴于您的数据结构:

>>> [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?'}

>>> account[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'account' is not defined

>>> accounts.get(2)
{'title': 'Gow to get this one?'}
>>> accounts.get(10)
# None

相关问题 更多 >