根据字典文件(JSON)测试用户输入

2024-10-04 11:36:30 发布

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

我有一个JSON文件,其中包含以下格式的大量项目列表:

[{"sku":43900,"name":"Duracell - AAA Batteries (4-Pack)","type":"HardGood","price":5.49,"upc":"041333424019","category": 
[{"id":"pcmcat312300050015","name":"Connected Home & Housewares"},{"id":"pcmcat248700050021","name":"Housewares"},{"id":"pcmcat303600050001","name":"Household Batteries"},{"id":"abcat0208002","name":"Alkaline Batteries"}],"shipping":5.49,"description":"Compatible with select electronic devices; AAA size; DURALOCK Power Preserve technology; 4-pack","manufacturer":"Duracell","model":"MN2400B4Z","url":"http://www.bestbuy.com/site/duracell-aaa-batteries-4-pack/43900.p?id=1051384074145&skuId=43900&cmp=RMXCC","image":"http://img.bbystatic.com/BestBuy_US/images/products/4390/43900_sa.jpg"},
{"sku":48530,"name":"Duracell - AA 1.5V CopperTop Batteries (4-Pack)","type":"HardGood","price":5.49,"upc":"041333415017","category":[{"id":"pcmcat312300050015","name":"Connected Home & Housewares"},{"id":"pcmcat248700050021","name":"Housewares"},{"id":"pcmcat303600050001","name":"Household Batteries"},{"id":"abcat0208002","name":"Alkaline Batteries"}],"shipping":5.49,"description":"Long-lasting energy; DURALOCK Power Preserve technology; for toys, clocks, radios, games, remotes, PDAs and more","manufacturer":"Duracell","model":"MN1500B4Z","url":"http://www.bestbuy.com/site/duracell-aa-1-5v-coppertop-batteries-4-pack/48530.p?id=1099385268988&skuId=48530&cmp=RMXCC","image":"http://img.bbystatic.com/BestBuy_US/images/products/4853/48530_sa.jpg"},

任务是提取“name:”so并将其拆分,以便: “名称”:“Duracell-AA 1.5V铜电池(4组)”

变成

{key: "Duracell": AA 1.5V CopperTop Batteries (4-Pack)}

这是我的代码:

import json
data = {}
json_data = json.load(open(r'C:\Users\fionna.pereira\Desktop\products.json', encoding='utf-8'))
for item in range(len(json_data)):
   x = json_data[item]["name"]
   if x is None:
       continue
   else:
       y = x.split(' - ', 1)
       data = {k: v for k, v in zip(y[::2], y[1::2])} # Turn list entry into key/value pairs
       for key, value in data.items() :
        print(data)

数据输出如下:

    {'Protec': 'Extended Life Wicking Filter for Select Humidifiers - White'}
{'Honeywell': 'True HEPA Replacement Filters for Select Honeywell Air Purifiers (2-Pack) - White'}
{'Dyson': 'Hard Floor Wipes for Dyson Hard DC56 Vacuums (1 Pack of 12 Wipes) - White'}
{'Aleratec': 'Drive Enclosure - Internal - Black'}
{'Amazon': 'Fire TV Stick'}
{'Proctor Silex': '4-Slice Toaster Oven - White'}

当我使用以下代码检索密钥时,为了测试拆分是否真的有效:

for key, value in data.items() :
        print(keys)

我收到输出(这是正确的):

Protec
Honeywell
Dyson
Aleratec
Amazon
Proctor Silex

当我使用以下内容检索值时:

for key, value in data.items() :
        print(values)

我收到以下输出(这也是正确的):

True HEPA Replacement Filters for Select Honeywell Air Purifiers (2-Pack) - White
Hard Floor Wipes for Dyson Hard DC56 Vacuums (1 Pack of 12 Wipes) - White
Drive Enclosure - Internal - Black
Fire TV Stick
4-Slice Toaster Oven - White

然而,当我要求用户输入一个键并返回一个值时,什么都没有出现?这是我用于输入的代码:

import json
data = {}
json_data = json.load(open(r'C:\Users\fionna.pereira\Desktop\products.json', encoding='utf-8'))
for item in range(len(json_data)):
   x = json_data[item]["name"]
   if x is None:
       continue
   else:
       y = x.split(' - ', 1)
       data = {k: v for k, v in zip(y[::2], y[1::2])} # Turn list entry into key/value pairs
       key = input('Enter the key: ')
       if key in data:
           print('The value is:', data[key])
       elif key.title() in data:
        print('The value is:', data[key.title()])

有人能告诉我哪里出了问题吗


Tags: keynameinidjsonhttpfordata
1条回答
网友
1楼 · 发布于 2024-10-04 11:36:30

如果您尝试此方法,希望它能更好地为您服务:

key = input('Enter the key: ')

for item in range(len(json_data)):
   x = json_data[item]["name"]
   if x is None:
       continue
   else:
       y = x.split(' - ', 1)
       data = {k.lower(): v for k, v in zip(y[::2], y[1::2])}
       if key.lower() in data:
           print('The value is:', data[key])

第一条语句只要求选择一次(您可以将其包装在另一个循环中以控制该选择),而不是要求用户提供数据中的每个元素

在循环中,您将滚动数据,查看用户条目是否与之匹配

我有点感兴趣的是,为什么您在提供的数据方面从未取得任何成功,但是如果该文件中有更多的项目,那么您将一次只匹配一个项目,因为您必须在循环中输入文件中每个项目的搜索项。;-)

对于稍微简单一点的版本,它应该非常容易扩展:

entered = input('Enter the key: ')

for item in json_data:
   if item["name"].find(" - ") > 0:
       name, item_desc = item["name"].split(' - ', 1)
       
       if entered.lower() == name.lower():
           print('The value is:', item_desc)

希望有帮助

相关问题 更多 >