1

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 the tables look like this:

list_id    list_items
1           apple
1           orange
2           fennel
2           basil
2           bay leaves
3           almonds
3           walnuts

The main thing that I don't know how to do is how to parse through the multiple values in the dictionary so that I have separate rows. I've looked into csv.writerow() but the documentation isn't very helpful, so examples are much appreciated!

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

4

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])
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251