How To Write Dictionary With Multiple Values To A Csv?
I have a dictionary that looks like this { 1: ['apple', 'orange'], 2: ['fennel', 'basil', 'bay leaves'], 3: ['almonds', 'walnuts']} I'm trying to export it into CSV and have t
Solution 1:
Loop through the dictionary keys/values, then loop through the values:
import csv
D = { 1: ['apple', 'orange'],
2: ['fennel', 'basil', 'bay leaves'],
3: ['almonds', 'walnuts']}
# with open('out.csv','w',newline='') as f: # Python 3
with open('out.csv','wb') as f: # Python 2
w = csv.writer(f)
w.writerow(['list_id','list_items'])
for key,items in D.items():
for item in items:
w.writerow([key,item])
Post a Comment for "How To Write Dictionary With Multiple Values To A Csv?"