我试图了解如何通过最接近的匹配来搜索 json 密钥对。所以我做了一些谷歌搜索并到达这里:https://linuxhint.com/search_json_python/
最终,我将示例 3 的代码复制并粘贴到我的 idle 中,它可以工作,但是如果我键入除完全匹配之外的任何内容(例如 Pe
而不是 Pen
),它会引发异常.
我基本上想找出为什么要打印任何不匹配但接近的搜索结果。 (有点像使用 os.walk 时)
代码如下:
#!/usr/bin/env python3
# Import json module
import json
# Define json variable
jsondata = """[
{
"name":"Pen",
"unit_price":5
},
{
"name":"Eraser",
"unit_price":3
},
{
"name":"Pencil",
"unit_price":10
},
{
"name":"White paper",
"unit_price":15
}
]"""
# load the json data
items = json.loads(jsondata)
# Input the item name that you want to search
item = input("Enter an item name:\n")
# Define a function to search the item
def search_price (name):
for keyval in items:
if name.lower() == keyval['name'].lower():
return keyval['unit_price']
# Check the return value and print message
if (search_price(item) != None):
print("The price is:", search_price(item))
else:
print("Item is not found")
任何想法或链接将不胜感激。
感谢您的时间,
答案 0 :(得分:0)
def search_price (name):
for keyval in items:
if name.lower() in keyval['name'].lower():
return keyval['unit_price']
请试试这个。
答案 1 :(得分:0)
@Olvin Roght 能够给我正确的答案,这对我有帮助:next(filter(lambda x: x["name"].startswith(item), items)) or next(x for x in items if x["name"].startswith(item))