将python字典写入CSV列:键到第一列,值为秒 [英] Write python dictionary to CSV columns: keys to first column, values to second

查看:686
本文介绍了将python字典写入CSV列:键到第一列,值为秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来将一个python字典写入列(第一列中的键和第二列中的值)。此链接显示了如何将列表写入列,但是想知道是否有办法可以将我的字典转换成两个压缩列表。

I'm looking for a way to write a python dictionary to columns (keys in first column and values in second). This link shows how to write a list to a column, but am wondering if there is a way to do this without converting my dictionary to two zipped lists.

myDict = {1:'a', 2:'b', 3:'c'}

keyList = myDict.keys()
valueList = myDict.values()

rows = zip(keyList, valueList)

with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow(row)

所需结果:

1;a
2;b
3;c


推荐答案

你可以简单地做:

with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for row in myDict.iteritems():
        writer.writerow(row)

这篇关于将python字典写入CSV列:键到第一列,值为秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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