Skip to content
Advertisement

Python: convert dictionary into a cvs file

This is my current code:

JavaScript

What I am trying to achieve is that the dictionary keys are turned into the csv headers and the values turned into the rows.

But when running the code I get a TypeError: 'string indices must be integers' in line 21.

Advertisement

Answer

Problem

The issue here is for row in data. This is actually iterating over the keys of your data dictionary, and then you’re iterating over the characters of the dictionary keys:

JavaScript

Approach

What you actually need to do is use zip to capture both the name and favorite language of each person at the same time:

JavaScript

Now, you need to zip those tuples with the keys from data:

JavaScript

Solution

Now you can pass these tuples to the dict constructor to create your rowdicts which csv_writer.writerows requires:

JavaScript

Output in output.csv:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement