从JSON数据库中提取数据(Python 3)

时间:2018-04-07 18:03:55

标签: json python-3.x dictionary

我想编写一个程序,将JSON数据库中的数据加载到字典的Python列表中,并添加平均温度高于冰点以下的所有次数。但是,我正在努力成功从数据库中提取信息/我担心我的算法已关闭。我的计划: 1)定义一个从json文件加载数据的函数。 2)定义从文件中提取信息的函数 3)使用提取的信息来计算温度高于或低于冰点的次数

import json

def load_weather_data(): #function 1: Loads data
    with open("NYC4-syr-weather-dec-2015.json", encoding = 'utf8') as w: #w for weather
        data = w.read()
        weather = json.loads(data)
        print(type(weather))
        return weather

def extract_temp(weather): #function 2: Extracts information on weather
    info = {}
    info['Mean TemperatureF'] = weather['Mean TemperatureF']#i keep getting a type error here
    return info

print("Above and blelow freezing")
weather = load_weather_data()
info = extract_temp(weather)
above_freezing = 0
below_freezing = 0
for temperature in weather: # summing the number of times the weather was above versus below freezing
    if info['Mean Temperature'] >32:
        above_freezing=above_freezing+1
    elif info['mean temperature']<32:
        below_freezing = below_freezing +1

print(above_freezing)
print(below_freezing)

如果您有任何想法,请告诉我!谢谢。

1 个答案:

答案 0 :(得分:0)

在开始循环之前,您试图从weather列表中提取温度,而实际上您应该为循环中的每个温度对象执行此操作。您尚未发布示例数据,但我认为weatherlist,您尝试将其用作dict。下面是一个修复,其中包含一些其他整洁的变化。

import json

# fixed: call with filename so that the function works on other files
def load_weather_data(filename): #function 1: Loads data
    with open(filename, encoding = 'utf8') as w: #w for weather
        # fixed: fewer steps
        return json.load(w)

# fixed: not needed, doesn't simply anything
#def extract_temp(weather): #function 2: Extracts information on weather
#    info = {}
#    info['Mean TemperatureF'] = weather['Mean TemperatureF']#i keep getting a type error here
#    return info

print("Above and blelow freezing")

weather = load_weather_data("NYC4-syr-weather-dec-2015.json")
above_freezing = 0
below_freezing = 0

for temperature in weather: # summing the number of times the weather was above versus below freezing
    if info['Mean Temperature'] > 32:
        above_freezing += 1
    # fixed: capitalized above... so assuming it should be here too
    elif info['Mean Temperature'] < 32:
        below_freezing += 1

print(above_freezing)
print(below_freezing)