【问题标题】:Find element in list of objects with explicit key value在具有显式键值的对象列表中查找元素
【发布时间】:2014-10-21 02:17:20
【问题描述】:

我在 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 python-2.7 types


【解决方案1】:

鉴于您的数据结构:

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

【讨论】:

  • 如果某些字典不包含密钥,使用if item.get('id') == 2 可能会更好
  • 至于为什么要使用数据结构,我可以说我只是被 HANDED 这样一个需要 ETL 工作的结构...并不是真正可选的,它是一个 [{...} ,{...}] 格式...只需查找任何所述对象中是否存在密钥即可解决特定需求。
【解决方案2】:

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

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

也许以 id-number 作为键的字典更合适,因为这使访问更容易:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 2012-07-13
      相关资源
      最近更新 更多