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

时间:2018-02-02 21:47:24

标签: 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]
    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

我该如何解决这个问题?我试过创建一个空字典“dict = {}”并添加这种方式,但仍然没有返回任何内容。

感谢所有帮助!

1 个答案:

答案 0 :(得分:1)

如果找不到任何内容,您还需要处理此案例。因此,返回一个空的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 {}