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

时间:2017-07-31 23:36:38

标签: python csv dictionary

我有一本看起来像这样的字典

{ 1: ['apple', 'orange'],
  2: ['fennel', 'basil', 'bay leaves'],
  3: ['almonds', 'walnuts']}

我尝试将其导出为CSV并让表格如下所示:

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

我不知道如何做的主要事情是如何解析字典中的多个值,以便我有单独的行。我已查看了csv.writerow(),但文档并不是非常有用,所以我非常感谢您的示例!

1 个答案:

答案 0 :(得分:2)

循环遍历字典键/值,然后遍历值:

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