在字典列表中查找项目

2024-10-03 23:27:08 发布

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

我有这些数据

data = [
    {
        'id': 'abcd738asdwe',
        'name': 'John',
        'mail': 'test@test.com',
    },
    {
        'id': 'ieow83janx',
        'name': 'Jane',
        'mail': 'test@foobar.com',
    }
]

id是唯一的,不可能多个听写都有相同的id

例如,我想获取id为“ieow83janx”的项。你知道吗

我当前的解决方案如下所示:

search_id = 'ieow83janx'
item = [x for x in data if x['id'] == search_id][0]

你认为这是最好的解决方案还是有人知道其他的解决方案?你知道吗


Tags: 数据nametestcomidsearchdatamail
3条回答

由于id是唯一的,因此可以将这些项存储在字典中以实现O(1)查找。你知道吗

lookup = {ele['id']: ele for ele in data}

那你就可以了

user_info = lookup[user_id]

去找回它

next内置函数(docs)如何:

>>> data = [
...     {
...         'id': 'abcd738asdwe',
...         'name': 'John',
...         'mail': 'test@test.com',
...     },
...     {
...         'id': 'ieow83janx',
...         'name': 'Jane',
...         'mail': 'test@foobar.com',
...     }
... ]
>>> search_id = 'ieow83janx'
>>> next(x for x in data if x['id'] == search_id)
{'id': 'ieow83janx', 'name': 'Jane', 'mail': 'test@foobar.com'}

编辑:

如果找不到匹配项,则会引发StopIteration,这是处理缺勤的一种很好的方法:

>>> search_id = 'does_not_exist'
>>> try:
...     next(x for x in data if x['id'] == search_id)
... except StopIteration:
...     print('Handled absence!')
... 
Handled absence!

如果要对这个特定对象多次执行此类操作,我建议将其转换为以id为键的字典。你知道吗

data = [
    {
        'id': 'abcd738asdwe',
        'name': 'John',
        'mail': 'test@test.com',
    },
    {
        'id': 'ieow83janx',
        'name': 'Jane',
        'mail': 'test@foobar.com',
    }
]

data_dict = {item['id']: item for item in data}
#=> {'ieow83janx': {'mail': 'test@foobar.com', 'id': 'ieow83janx', 'name': 'Jane'}, 'abcd738asdwe': {'mail': 'test@test.com', 'id': 'abcd738asdwe', 'name': 'John'}}

data_dict['ieow83janx']
#=> {'mail': 'test@foobar.com', 'id': 'ieow83janx', 'name': 'Jane'}

在这种情况下,此查找操作将花费一些固定的*O(1)时间,而不是O(N)。你知道吗

相关问题 更多 >