Python 将列表字典写入CSV文件

Python 将列表字典写入CSV文件,python,csv,dictionary,Python,Csv,Dictionary,我正在努力将列表字典写入.csv文件 我的字典是这样的: dict[key1]=[1,2,3] dict[key2]=[4,5,6] dict[key3]=[7,8,9] key1 key2 key3 1 4 7 2 5 8 3 6 9 我希望.csv文件看起来像: key1 key2 key3 1 4 7 2 5 8 3 6 9 首先,我写标题: outputfile = open

我正在努力将列表字典写入.csv文件

我的字典是这样的:

dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[key3]=[7,8,9]
key1  key2  key3
1     4     7
2     5     8
3     6     9
我希望.csv文件看起来像:

key1  key2  key3
1     4     7  
2     5     8
3     6     9
首先,我写标题:

outputfile = open (file.csv,'wb')
writefile = csv.writer (outputfile)
writefile.writerow(dict.keys())
到目前为止还不错。。。然而,我的问题是,我不知道如何将一个列表分配给相应的列。e、 g:

for i in range(0,len(dict[key1])):
    writefile.writerow([dict[key1][i],dict[key2][i],dict[key3][i])

将随机填充列。另一个问题是,我必须手动填写键,不能将其用于另一个有4个键的字典。

如果您不关心列的顺序(因为字典是无序的),您可以简单地使用
zip()

结果:

key3    key2    key1
7       4       1
8       5       2
9       6       3
key1    key2    key3
1       4       7
2       5       8
3       6       9
如果您确实关心顺序,则需要对键进行排序:

keys = sorted(d.keys())
with open("test.csv", "wb") as outfile:
   writer = csv.writer(outfile, delimiter = "\t")
   writer.writerow(keys)
   writer.writerows(zip(*[d[key] for key in keys]))
结果:

key3    key2    key1
7       4       1
8       5       2
9       6       3
key1    key2    key3
1       4       7
2       5       8
3       6       9
给定

以下代码:

COL_WIDTH = 6
FMT = "%%-%ds" % COL_WIDTH

keys = sorted(dict.keys())

with open('out.csv', 'w') as csv:
    # Write keys    
    csv.write(''.join([FMT % k for k in keys]) + '\n')

    # Assume all values of dict are equal
    for i in range(len(dict[keys[0]])):
        csv.write(''.join([FMT % dict[k][i] for k in keys]) + '\n')
生成一个csv,看起来像:

dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[key3]=[7,8,9]
key1  key2  key3
1     4     7
2     5     8
3     6     9

在不使用csv模块的情况下推出您自己的:

d = {'key1' : [1,2,3],
     'key2' : [4,5,6],
     'key3' : [7,8,9]}

column_sequence = sorted(d.keys())
width = 6
fmt = '{{:<{}}}'.format(width)
fmt = fmt*len(column_sequence) + '\n'

output_rows = zip(*[d[key] for key in column_sequence])

with open('out.txt', 'wb') as f:
    f.write(fmt.format(*column_sequence))
    for row in output_rows:
        f.write(fmt.format(*row))
d={'key1':[1,2,3],
'键2':[4,5,6],
'key3':[7,8,9]}
列顺序=已排序(d.键())
宽度=6
fmt='{{:保存:
重读:

即使键中的列表长度不同,这也会起作用

    with myFile:  
        writer = csv.DictWriter(myFile, fieldnames=list(clusterWordMap.keys()))   
        writer.writeheader()
        while True:
            data={}
            for key in clusterWordMap:
                try:
                    data[key] = clusterWordMap[key][ind]
                except:
                    pass
            if not data:
                break
            writer.writerow(data)
您可以使用pandas将其保存到csv:

df = pd.DataFrame({key: pd.Series(value) for key, value in dictmap.items()})
df.to_csv(filename, encoding='utf-8', index=False)

“随机填充列”是什么意思?@RobWatts我认为OP的意思是因为
dict
s是无序的,所以函数
keys()
将“随机”打印出来例如,键3,键1,键2顺便说一句,你不应该使用
dict
作为变量名。
dict
不是我真正的变量名…只是一个糟糕的例子我们如何在这里将行更改为列键1\tab 7\tab 4\tab 1如果你看这个问题,我使用了
zip()
转换原始数据。如果您再次执行该操作,您将再次将行更改为列。请注意,
key1-7-4-1
可能不是您想要的…这为我运行,我得到了我想要的输出,但它仍然抛出一个typeError“zip参数#1必须支持迭代”。有什么原因吗?是的,在Python 2上,你需要使用
wb
,而在Python 3上,当打开CSV文件时,你需要使用
newline=''
选项。@JasonGoal可能已经很晚了,但如果你仍然想知道答案,这里有一个要点,该人对其进行了完美的解释df=pd.DataFrame(dict)是创建数据帧所需的全部。如果字典中存储的值长度不同,则该操作将失败
df = pd.DataFrame({key: pd.Series(value) for key, value in dictmap.items()})
df.to_csv(filename, encoding='utf-8', index=False)