[英]Python dictionary to CSV in required format
I have a python dictionary that looks like the following: 我有一个看起来像以下的python字典:
{
key1: [value1, value2, value3, n],
key2: [value1, value2, value3, n],
key3: [value1, value2, value3, n],
key4: [value1, value2, value3, n]
}
I would like to write these values to a csv file in the format where each line contains Keys as header and associated values(row by row) under that key. 我想将这些值写入格式为csv的文件中,其中每一行都包含Keys作为标题和该Key下的相关值(逐行)。
pandas
provides a very straight forward solution to the problem - pandas
提供了非常直接的解决方案-
import pandas as pd
df = pd.DataFrame({
'key1': ['value1', 'value2', 'value3', 'n'],
'key2': ['value1', 'value2', 'value3', 'n'],
'key3': ['value1', 'value2', 'value3', 'n'],
'key4': ['value1', 'value2', 'value3', 'n']
})
df.to_csv('/path/to/file')
Perhaps pandas
can provide you with a more direct way of achieving this, but if you simply want to rely on the csv
package from the standard library, the following naive approach should do: 也许
pandas
可以为您提供更直接的方法来实现这一目标,但是如果您只想依赖标准库中的csv
包,则可以采用以下朴素的方法:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
data = {
'key1': ['value1', 'value2', 'value3', 'n'],
'key2': ['value1', 'value2', 'value3', 'n'],
'key3': ['value1', 'value2', 'value3', 'n'],
'key4': ['value1', 'value2', 'value3', 'n']
}
header = data.keys()
no_rows = len(data[list(header)[0]])
with open('out.csv', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerow(header)
for row in range(no_rows):
csvwriter.writerow([data[key][row] for key in header])
This results in 这导致
key1,key2,key3,key4
value1,value1,value1,value1
value2,value2,value2,value2
value3,value3,value3,value3
n,n,n,n
Hope this helps! 希望这可以帮助!
EDIT 编辑
Since this is now the accepted answer, I feel that I should add that pandas.DataFrame.to_csv
does indeed provide a more direct way of achieving this, as mentioned in other answers: 由于这是现在公认的答案,因此我觉得我应该补充一点
pandas.DataFrame.to_csv
确实确实提供了一种更直接的方法来实现这一点,如其他答案所述:
import pandas as pd
pd.DataFrame(data).to_csv('out.csv', index=False)
produces the same output as above (possibly with different line terminators, depending on your system). 产生与上述相同的输出(可能使用不同的线路终结器,具体取决于您的系统)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.