gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:49 25 4
gpt4 key购买 nike

显然,这是初学者会问的问题。但是,我正在努力将键添加到我的字典中以纠正以下错误:

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={}”并以这种方式添加,但仍然没有返回任何内容。

感谢所有帮助!

最佳答案

如果没有发现任何情况,您还需要处理该案件。因此,返回一个空字典而不是 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 {}

关于python - 如何在 Python 中使用键创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48591296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com