[英]Write python dictionary to CSV columns: keys to first column, values to second
I'm looking for a way to write a python dictionary to columns (keys in first column and values in second). 我正在寻找一种方法来写一个python字典到列(第一列中的键和第二列中的值)。 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)
desired result: 期望的结果:
1;a
2;b
3;c
You could simply do: 你可以这样做:
with open('test.csv', 'wb') as f:
writer = csv.writer(f)
for row in myDict.iteritems():
writer.writerow(row)
A slightly shorter version is to do: 一个稍短的版本是:
rows = myDict.iteritems()
(Or .items()
for Python 3.) (或
.items()
for Python 3.)
To get the ;
获得
;
separator, pass delimiter
to csv.reader
or csv.writer
. 分隔符,将
delimiter
传递给csv.reader
或csv.writer
。 In this case: 在这种情况下:
writer = csv.writer(f, delimiter=';')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.