简体   繁体   English

Python json 按特定键值在列表中查找字典

[英]Python json find dictionary in list by specific key value

I was using api to get information about bus lines and got a list of dictionaries of the information.我正在使用 api 来获取有关公交线路的信息,并获得了该信息的字典列表。

Below are examples.以下是示例。

list = [{'start':'location A',
 'end':'location B',
 'routeNo':'1'},
{'start':'location C',
 'end':'location D',
 'routeNo':'2'},
{'start':'location E',
 'end':'location F',
 'routeNo':'3'}]

I am trying to get the whole dictionary of specific route by its 'routeNo'.我试图通过它的'routeNo'来获取特定路线的整个字典。 For example I want to use '3' to get information of this route.例如,我想使用 '3' 来获取这条路线的信息。 Expected result is below.预期结果如下。

{'start':'location E',
 'end':'location F',
 'routeNo':'3'}

The closest thing I have tried is我尝试过的最接近的事情是

print(list[2])

It's no ideal because I am not searching it, I am just getting the third item in list.这并不理想,因为我没有搜索它,我只是得到列表中的第三项。

So I am looking for other ways to get the result.所以我正在寻找其他方法来获得结果。 Thanks.谢谢。

Here is how you could search it:以下是您如何搜索它:

def find_route(data, route_no):
    return list(filter(lambda x: x.get('rounteNo') == route_no, data))

route = find_rounte(route_list, '3')

Note i renamed list to route_list .注意我将list重命名为route_list That is because list is a built-in function and you've overwritten, which is a bad practice.那是因为list是一个内置的 function 并且你已经覆盖了,这是一个不好的做法。

Also, assuming you are a beginner, here is a simpler to understand version:另外,假设您是初学者,这里有一个更易于理解的版本:

def find_route(data, route_no):
    return [route for route in data if route.get('rounteNo') == route_no]

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

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