I'm trying to create a csv file from a list of dictionary items where each dictionary in the list has the same keys. I want the csv file to have the keys in the first column and the remaining columns will have the values for each dictionary in the list corresponding to the key.
My desired output is:item1,3,2,18
item2,3,6,12
item3,5,3,1
The following code works but it seems there should be a more elegant way to do this.
l = [
{'item1':3, 'item2':3, 'item3':5},
{'item1':2, 'item2':6, 'item3':3},
{'item1':18, 'item2':12, 'item3':1} ]
str_list = []
for d in l:
str_list.append(str(d['item1']))
str_list.insert(0,'item1')
out = ','.join(str_list)
print(out)
str_list = []
for d in l:
str_list.append(str(d['item2']))
str_list.insert(0,'item2')
out = ','.join(str_list)
print(out)
str_list = []
for d in l:
str_list.append(str(d['item3']))
str_list.insert(0,'item3')
out = ','.join(str_list)
print(out)