0

I want to Convert my python Dictionary to .csv file where Dictionary consists of "keywordvalue":[listofdata] with that said i want my csv file to look in such way that keyword value is column in csv file and data inside list will stay in that column corresponding to the key. Example -->

my_dict={"date":['11/2/19','3/11/20'],"name":['dexter','morgan']

CSV_file output -->

date,name
'11/2/19','dexter'
'3/11/20','morgan'
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
tracer
  • 41
  • 3

2 Answers2

4

Use csv module:

import csv

field_names = ['Date', 'Name']

my_dict=[{"date":'11/2/19',"name":'dexter'}, {"date":'3/11/20',"name":'morgan'}]

with open('file.csv', 'w') as csvfile: 
    writer = csv.DictWriter(csvfile, fieldnames = field_names) 
    writer.writeheader() 
    writer.writerows(my_dict)

for more information check: https://www.geeksforgeeks.org/how-to-save-a-python-dictionary-to-a-csv-file/

Amin Baqershahi
  • 361
  • 4
  • 11
0

You will have to munge your dict a bit, but something like this would work:

import csv

field_names = ['date', 'name']

my_dict={"date":['11/2/19','3/11/20'],"name":['dexter','morgan']}

with open('file.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(field_names)
    rows = zip(*[my_dict[name] for name in field_names])
    writer.writerows(rows)

This use of zip is a common idiom for "transposing", so:

zip(*[my_dict[name] for name in field_names])

So, for example:

In [2]: my_dict={"date":['11/2/19','3/11/20'],"name":['dexter','morgan']}

In [2]: field_names = ['date', 'name']

In [3]: list(zip(*[my_dict[name] for name in field_names]))
Out[3]: [('11/2/19', 'dexter'), ('3/11/20', 'morgan')]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172