This is my current code:
JavaScript
x
20
20
1
import csv
2
data = {'name' : ['Dave', 'Dennis', 'Peter', 'Jess'],
3
'language': ['Python', 'C', 'Java', 'Python']}
4
5
new_data = []
6
for row in data:
7
new_row = {}
8
for item in row:
9
new_row[item['name']] = item['name']
10
new_data.append(new_row)
11
12
print(new_data)
13
header = new_data[0].keys()
14
print(header)
15
16
with open('output.csv', 'w') as fh:
17
csv_writer = csv.DictWriter(fh, header)
18
csv_writer.writeheader()
19
csv_writer.writerows(new_data)
20
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
1
21
21
1
In [2]: data = {'name' : ['Dave', 'Dennis', 'Peter', 'Jess'],
2
'language': ['Python', 'C', 'Java', 'Python']} :
3
:
4
new_data = [] :
5
for row in data: :
6
for item in row: :
7
print(item) :
8
:
9
n
10
a
11
m
12
e
13
l
14
a
15
n
16
g
17
u
18
a
19
g
20
e
21
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
1
8
1
In [43]: for row in zip(*data.values()):
2
print(row) :
3
:
4
('Dave', 'Python')
5
('Dennis', 'C')
6
('Peter', 'Java')
7
('Jess', 'Python')
8
Now, you need to zip
those tuples with the keys from data
:
JavaScript
1
9
1
In [44]: header = data.keys()
2
for row in zip(*data.values()): :
3
print(list(zip(header, row))) :
4
:
5
[('name', 'Dave'), ('language', 'Python')]
6
[('name', 'Dennis'), ('language', 'C')]
7
[('name', 'Peter'), ('language', 'Java')]
8
[('name', 'Jess'), ('language', 'Python')]
9
Solution
Now you can pass these tuples to the dict
constructor to create your rowdicts
which csv_writer.writerows
requires:
JavaScript
1
10
10
1
header = data.keys()
2
new_data = []
3
for row in zip(*data.values()):
4
new_data.append(dict(zip(header, row)))
5
6
with open("output.csv", "w+", newline="") as f_out:
7
csv_writer = csv.DictWriter(f_out, header)
8
csv_writer.writeheader()
9
csv_writer.writerows(new_data)
10
Output in output.csv
:
JavaScript
1
6
1
name,language
2
Dave,Python
3
Dennis,C
4
Peter,Java
5
Jess,Python
6