在 JSON (Python) 中查找元素的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45414082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The Fastest method to find element in JSON (Python)
提问by Hero Guy
I have Json:
我有 Json:
[
{
"name":"Apple",
"price":2,
"have":0,
"max":36
},
{
"name":"Pineapple",
"price":5,
"have":6,
"max":17
}
]
I need the fastest function, that receives name, and sends price. For example for print(jsonname("Apple")) is 2.
我需要最快的函数,即接收名称并发送价格。例如对于 print(jsonname("Apple")) 是 2。
P.S. Please do not post Loop answers, I know them. I need fast methods and names of methods
PS请不要发布循环答案,我知道他们。我需要快速方法和方法名称
回答by Y2H
Here's an easy way to do it:
这是一个简单的方法:
def function(json_object, name):
for dict in json_object:
if dict['name'] == name:
return dict['price']
If you are sure that there are no duplicate names, an even more effective (and pythonic) way to do it is to use list comprehensions:
如果您确定没有重复的名称,则更有效(和pythonic)的方法是使用列表推导式:
def function(json_object, name):
return [obj for obj in json_object if obj['name']==name][0]['price']
回答by marsouf
from json import loads
json = """[
{
"name":"Apple",
"price":2,
"have":0,
"max":36
},
{
"name":"Pineapple",
"price":5,
"have":6,
"max":17
}
]"""
parsedJson = loads (json)
def jsonname (name):
for entry in parsedJson:
if name == entry ['name']:
return entry ['price']