【问题标题】:How to Create Dictionary in Python with Keys如何在 Python 中使用键创建字典
【发布时间】:2018-07-13 11:06:57
【问题描述】:

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

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

感谢所有帮助!

【问题讨论】:

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

标签: python dictionary output typeerror


【解决方案1】:

如果一无所获,您也需要处理此案。因此,返回一个空字典而不是 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 {}

【讨论】:

    猜你喜欢
    • 2013-04-12
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    相关资源
    最近更新 更多