简体   繁体   English

如何将具有多个值的字典写入CSV?

[英]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: 我正在尝试将其导出为CSV,并使表格如下所示:

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! 我已经研究过csv.writerow()但是该文档并不是很有帮助,因此示例非常感谢!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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