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

时间:2014-08-27 13:12:28

标签: 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的对象。

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

3 个答案:

答案 0 :(得分:8)

鉴于您的数据结构:

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

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

答案 1 :(得分:0)

这将返回列表中具有id == 2

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

答案 2 :(得分:0)

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

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

也许将id-number作为键的字典更合适,因为这样可以更轻松地访问:

account_dict = {account['id']: account for account in accounts}
相关问题