简体   繁体   中英

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 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!

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM