任何人都可以指出我做错了什么。我试图将用户输入与数组匹配,但似乎没有得到任何响应。任何帮助都很棒。谢谢。
`#import json module to read json file
import json
#open then read file and close file
fin=open("weather-data.json","r")
json_string=fin.read()
fin.close()
#Json to python dictionary
array=json.loads(json_string)
#User input
desired_month=input("Input a month number 1 -5:")
desired_day=input("Pick a day in the month:")
#matching day and month to dic.
for d in array:
if desired_month==d["month"] and desired_day==d["day"]:
print (d[{"high"}],d[{"low"}])
`
weather-data.json具有以下格式:
[
{
"year": 2014,
"month": 1,
"day": 1,
"high": 22,
"low": 16,
"precip": 0.25
},
{
"year": 2014,
"month": 1,
"day": 2,
"high": 21,
"low": 10,
"precip": 0.22
}, ...
]
答案 0 :(得分:1)
主要问题是您将desired_month
和desired_day
存储为字符串,而JSON文件将它们存储为整数。因此,您希望的值与存储在JSON中的值之间的比较总是会计算为False
,并且永远不会打印高温和低温。
第二个问题是在打印高温和低温时存在Python语法错误。在给定密钥的情况下访问字典值的语法是d["high"]
,而不是d[{"high"}]
。
以下是经过修改的修正版本(weather.py
):
import json
# Load JSON
with open("weather-data.json") as weather_data_file:
weather_list = json.load(weather_data_file)
# Get user inputs (as strings) and convert them integers for later comparison
desired_month = int(input("Input a month number 1 -5:"))
desired_day = int(input("Pick a day in the month:"))
# matching day and month to content of JSON file
for weather_entry in weather_list:
if desired_month == weather_entry["month"] and desired_day == weather_entry["day"]:
print(weather_entry["high"], weather_entry["low"])
程序的示例输出:
➜ python weather.py
Input a month number 1 -5:2
Pick a day in the month:25
22 6