简体   繁体   English

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

[英]How to get a value from a list of dictionary Python?

I have a list(stop_list) of dictionary. 我有一个字典清单(stop_list)。 the structure of dictionary is 字典的结构是

stop_id : ""
stop_name : ""

Now, I have a name string which is to be matched against stop_name , and get the stop_id corresponding to that. 现在,我有了一个名称字符串,该字符串将与stop_name匹配,并获取stop_id对应的stop_id

Is there any efficient way of doing it? 有什么有效的方法吗? I could come up with only for loop. 我只能提出for循环。

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

You can use generator expression and next function, like this 您可以像这样使用生成器表达式和next函数

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

This will iterate through the stop_list and when it finds a match, it will yield entry['id'] . 这将在stop_list进行迭代,并在找到匹配entry['id']时产生entry['id'] This will be better because this doesn't have to iterate the entire list. 这样做会更好,因为不必迭代整个列表。

Another advantage is, if there are more than one matches, then you can use the same expression to get the next id also, like this 另一个好处是,如果有多个匹配项,那么您也可以使用相同的表达式来获取下一个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

If there is going to be more than one lookups, and given the names are unique, then preprocess the list and create a dictionary, like this 如果要进行多个查找,并且名称是唯一的,则对列表进行预处理并创建一个字典,如下所示

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

then you can do lookups in constant time, with lookup[name] . 那么您可以使用lookup[name]在固定时间内进行lookup[name] This would be the most efficient way if the names are unique and if there are more than one lookups 如果名称是唯一的并且查找不止一个,这将是最有效的方法

After looking at the code it seems that you get the dictionary having the same name. 看完代码后,您似乎得到了具有相同名称的字典。 If your name are unique you should consider using a dict for your dicts where the key would be the name. 如果您的名字是唯一的,则应考虑将dict用作名称的键。

1 - this will allow you not to browse the list (it is costly compared to dict lookup) 1-这将使您无法浏览列表(与dict查找相比,它的成本很高)

2 - this is more readable 2-这更具可读性

3 - you call entry['name'] only once 3-您只需调用一次entry ['name']

Let's say that your stopdict would look like that 假设您的stopdict看起来像这样

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

accessing the id would look like that : 访问id看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM