sagaderisa sagaderisa - 6 months ago 18
Python Question

writing a nested dictionary to csv file

Novice question: I'm trying to write a function to write a nested dictionary to a csv file, so I pulled some code from Stack Overflow (Convert Nested Dictionary to CSV Table), but I keep getting the error message that "dict" isn't callable. Since I don't really understand what that part of the code is doing it's tough to troubleshoot.
Can someone please explain and help me fix my code?

Here's my code:

def dict_to_csv(dict, txtFileName, destination_file):

with open(destination_file, 'wb') as f:
writer = csv.DictWriter(f, dict.keys())
writer.writeheader()
for key, row in dict.iteritems():
writer.writerow(dict(row, **{'': key})) #this is the row where I'm getting the error message
f.closed()


Thanks in advance for your help!

Here is a sample of the dictionary I'm using:
{'20140524X21540': {'': '', 'Amateur Built': 'Yes', 'Make': 'KENNETH A BERGER', 'Location': '" Electric City, WA "', 'Total Uninjured': '', 'Latitude': '', 'Event Id': '20140524X21540', 'Airport Name': 'N/A', 'Aircraft Category': 'Unknown', 'Investigation Type': 'Accident', 'Report Status': 'Preliminary', 'Event Date': '05/24/2014', 'Total Fatal Injuries': '1', 'Country': 'United States', 'Weather Condition': 'VMC', 'Registration Number': 'N249PW', 'Accident Number': 'WPR14FA209', 'Number of Engines': '', 'Longitude': '', 'Air Carrier': '', 'Total Serious Injuries': '', 'Airport Code': '', 'Model': 'SEAREY LSX', 'Broad Phase of Flight': '', 'Publication Date': '05/29/2014', 'FAR Description': 'Part 91: General Aviation', 'Engine Type': '', 'Schedule': '', 'Purpose of Flight': 'Personal', 'Aircraft Damage': 'Substantial', 'Injury Severity': 'Fatal(1)', 'Total Minor Injuries': ''}, '20140529X73728': {'': '', 'Amateur Built': '', 'Make': 'ROBINSON HELICOPTER COMPANY', 'Location': '" Chugiak, AK "', 'Total Uninjured': '', 'Latitude': '61.417778', 'Event Id': '20140529X73728', 'Airport Name': '', 'Aircraft Category': 'Helicopter', 'Investigation Type': 'Accident', 'Report Status': 'Preliminary', 'Event Date': '05/28/2014', 'Total Fatal Injuries': '1', 'Country': 'United States', 'Weather Condition': 'VMC', 'Registration Number': 'N392GP', 'Accident Number': 'ANC14FA030', 'Number of Engines': '1', 'Longitude': '-149.500833', 'Air Carrier': '', 'Total Serious Injuries': '', 'Airport Code': '', 'Model': 'R44 II', 'Broad Phase of Flight': '', 'Publication Date': '05/30/2014', 'FAR Description': 'Part 133: Rotorcraft Ext. Load', 'Engine Type': 'Reciprocating', 'Schedule': '', 'Purpose of Flight': 'External Load', 'Aircraft Damage': 'Destroyed', 'Injury Severity': 'Fatal(1)', 'Total Minor Injuries': ''}, '20140320X40839': {'': '', 'Amateur Built': 'No', 'Make': 'CESSNA', 'Location': '" Charlottesville, VA "', 'Total Uninjured': '1', 'Latitude': '38.139722', 'Event Id': '20140320X40839', 'Airport Name': 'CHARLOTTESVILLE-ALBEMARLE', 'Aircraft Category': 'Airplane', 'Investigation Type': 'Accident', 'Report Status': 'Probable Cause', 'Event Date': '03/08/2014', 'Total Fatal Injuries': '', 'Country': 'United States', 'Weather Condition': 'VMC', 'Registration Number': 'N5423J', 'Accident Number': 'ERA14CA160', 'Number of Engines': '1', 'Longitude': '-78.452222', 'Air Carrier': '', 'Total Serious Injuries': '', 'Airport Code': 'CHO', 'Model': '172N', 'Broad Phase of Flight': 'LANDING', 'Publication Date': '05/05/2014', 'FAR Description': 'Part 91: General Aviation', 'Engine Type': 'Reciprocating', 'Schedule': '', 'Purpose of Flight': 'Personal', 'Aircraft Damage': 'Substantial', 'Injury Severity': 'Non-Fatal', 'Total Minor Injuries': ''}}

Answer

First off, don't use object names like dict as variables. That error is coming up because you're trying to call the variable dict.

In the code you mentioned, the purpose of the dict(...) line is to convert that defaultdict to a regular dict to prevent new keys from being created unintentionally. That usage of dict(...) is similar to a code snippet like this:

a = [1,2,3,4,5] # list
b = set(a) # conversion to set

The fix is easy: change your variable name!

def dict_to_csv(my_dict, txtFileName, destination_file):

    with open(destination_file, 'wb') as f:
        writer = csv.DictWriter(f, my_dict.keys())
        writer.writeheader()
        for key, row in my_dict.iteritems():
            writer.writerow(dict(row, **{'': key})) #this is the row where I'm getting the error message
    f.closed()