如何将具有多个值的字典写入CSV? [英] How to write dictionary with multiple values to a CSV?

查看:95
本文介绍了如何将具有多个值的字典写入CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本像这样的字典

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

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

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

我不知道该怎么做的主要事情是如何解析字典中的多个值,以便有单独的行.我已经研究过csv.writerow(),但是文档不是很有帮助,因此非常感谢示例!

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

这篇关于如何将具有多个值的字典写入CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆