简体   繁体   English

将python字典写入CSV列:第一列的键,第二列的值

[英]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.readercsv.writer In this case: 在这种情况下:

writer = csv.writer(f, delimiter=';')

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

相关问题 将 Python 字典写入 CSV,其中键 = 列,值 = 行 - Write Python dictionary to CSV where where keys= columns, values = rows Python - 根据代表列和行(坐标)的 position 的键将字典中的值写入.csv - Python - Write Values from Dictionary into .csv according to keys representing the position of column and row (coordinates) 如何在Python中编写具有多个键的字典,每个键具有多个值到csv? - How to write a dictionary with multiple keys, each with multiple values to a csv in Python? 将字典(键和值)写入csv文件 - Write dictionary (keys and values) to a csv file 将字典值写入csv python - Write dictionary values to csv python 带有列匹配的csv文件的Python字典键 - Python dictionary keys to csv file with column match 按列将字典正确写入csv python文件 - correctly write a dictionary into a csv python file by columns python dataframe 到具有多个键和值列的字典 - python dataframe to dictionary with multiple columns in keys and values 如何将字典的动态值写入 csv python - How to write Dynamic Values of Dictionary into csv python 如何创建具有 2 个键的字典,其中第一个键是索引,第二个键来自列表,值来自 df 的列? - How can I create a dictionary with 2 keys where the the first key is the index, the second key is from a list and the values from columns of a df?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM