在对象列表中根据显式键值查找元素

24 投票
4 回答
62162 浏览
提问于 2025-04-18 18:42

我在Python里有一个对象列表:

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

我需要找到一个id等于2的对象。

当我只知道对象的属性值时,怎么才能从这个列表中选出合适的对象呢?

4 个回答

0

这看起来像是一个奇怪的数据结构,但其实是可以实现的:

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

也许用一个字典,把ID号当作键会更合适,因为这样访问起来更简单:

account_dict = {account['id']: account for account in accounts}
1

这段代码会返回列表中任何一个id等于2的元素。

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

其他的回答都很老旧了。最好的方法是用 next()

next(account for account in accounts if account['id'] == 2)

可以查看这个链接了解更多:https://stackoverflow.com/a/9868665/1812732

34

根据你的数据结构:

>>> [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 来直接访问数据,或者使用 get() 方法,这取决于你想如何处理不存在的键。

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

撰写回答