user5834454
user5834454

Reputation: 147

How to Create Dictionary in Python with Keys

Obviously, this is a question a beginner would ask. However, I am struggling adding keys to my dictionary to correct the following errors:

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])

returns the error, below:

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

How would I go about fixing this? I've tried creating an empty dictionary "dict={}" and adding that way, but still returns nothing.

All help is appreciated!

Upvotes: 1

Views: 524

Answers (1)

Mike M&#252;ller
Mike M&#252;ller

Reputation: 85442

You also need to handle the case if nothing is found. Therefore, return an empty dict instead of None, i.e. having no return that is executed:

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 {}

Upvotes: 1

Related Questions