如何从Python字典列表中获取值?

2024-04-26 18:55:25 发布

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

我有一本字典的目录。词典的结构是

stop_id : ""
stop_name : ""

现在,我有一个要与stop_name匹配的名称字符串,并得到与之对应的stop_id。你知道吗

有什么有效的方法吗?我只能想出一个循环。你知道吗

for entry in stop_list:
            if name = entry['name']:
                id = entry['id']
                break

Tags: 方法字符串namein目录名称idfor
2条回答

在看了代码之后,你似乎得到了同名词典。 如果你的名字是唯一的,你应该考虑用一个dict作为你的dict,其中键就是名字。你知道吗

1-这将允许您不浏览列表(与dict查找相比成本高昂)

2-更具可读性

3-只调用entry['name']一次

假设你的stopdict是这样的

stopdict= {
    'stop1' : {'name' : 'stop1', 'id' : 1}
    'stop2' : {'name' : 'stop2', 'id' : 2}
}

访问id的方式如下:

stopdict[entry['name']]['id']

可以使用生成器表达式和next函数,如下所示

next(entry['id'] for entry in stop_list if entry['name'] == name)

这将遍历stop_list,当它找到匹配项时,它将产生entry['id']。这会更好,因为这不必迭代整个列表。你知道吗

另一个优点是,如果有多个匹配项,那么也可以使用相同的表达式来获取下一个id,如下所示

>>> ids = next(entry['id'] for entry in stop_list if entry['name'] == name)
>>> next(ids)
# you will get the first matching id here
>>> next(ids)
# you will get the second matching id here

如果要进行多个查找,并且给定名称是唯一的,那么请预处理列表并创建字典,如下所示

lookup = {entry['name']: entry['id'] for entry in stop_list}

然后您可以使用lookup[name]在固定时间内进行查找。如果名称是唯一的并且有多个查找,这将是最有效的方法

相关问题 更多 >