如何使用键在Python中创建字典

如何使用键在Python中创建字典,python,dictionary,output,typeerror,Python,Dictionary,Output,Typeerror,显然,这是一个初学者会问的问题。但是,我正在努力向字典添加关键字以更正以下错误: import csv, json, sys def find_deep_value(d, key): # Modified from https://stackoverflow.com/questions/48568649/convert-json-to-csv-using-python/48569129#48569129 if key in d: return d[key] f

显然,这是一个初学者会问的问题。但是,我正在努力向字典添加关键字以更正以下错误:

import csv, json, sys

def find_deep_value(d, key):
# Modified from https://stackoverflow.com/questions/48568649/convert-json-to-csv-using-python/48569129#48569129

    if key in d:
        return d[key]
    for k in d.keys():
        if isinstance(d[k], dict):
            for j in find_deep_value(d[k], key):
                return j

inputFile = open("pywu.cache.json", 'r')  # open json file
outputFile = open("CurrentObs.csv", 'w')  # load csv file
data = json.load(inputFile)  # load json content
inputFile.close()  # close the input file
output = csv.writer(outputFile)  # create a csv.write

# Gives you latitude coordinates from within the json
lat = find_deep_value(data, "latitude")

# Gives you longitude coordinates from within the json
lon = find_deep_value(data, "longitude")

# Gives you a list of weather from within the json
weather = find_deep_value(data, "weather")

# Gives you a list of temperature_strings from within the json
temp = find_deep_value(data, "temperature_string")

output.writerow([lat, lon, weather, temp])
返回错误,如下所示:

outputFile.close()
  File "json_to_csv.py", line 20, in <module>
    lat = find_deep_value(data, "latitude")
  File "json_to_csv.py", line 10, in find_deep_value
    for j in find_deep_value(d[k], key):
  File "json_to_csv.py", line 10, in find_deep_value
    for j in find_deep_value(d[k], key):
TypeError: 'NoneType' object is not iterable
outputFile.close()
文件“json_to_csv.py”,第20行,在
lat=查找深度值(数据,“纬度”)
文件“json_to_csv.py”,第10行,在find_deep_值中
对于find_deep_值(d[k],键)中的j:
文件“json_to_csv.py”,第10行,在find_deep_值中
对于find_deep_值(d[k],键)中的j:
TypeError:“非类型”对象不可编辑
我该如何着手解决这个问题?我尝试创建一个空字典“dict={}”,并以这种方式添加,但仍然没有返回任何结果


感谢您的帮助

如果什么也没找到,你还需要处理这个案子。因此,返回一个空的dict而不是
None
,即没有执行的
return

def find_deep_value(d, key):
    if key in d:
        return d[key]
    for k in d.keys():
        if isinstance(d[k], dict):
            for j in find_deep_value(d[k], key):
                return j
    return {}

您需要在这里提供一个有点离题的主题,但如果您想要将Json转换为csv,您是否考虑过使用pandas库?它有一个只在一行中实现这一点的方法。我能够运行python命令,“dict=dict.keys(['lation'、'longitude'、'weather'、'temp']),它似乎添加了适当的键。但是,脚本只返回值的第一个字母/字符。