将列表字典写入CSV文件

时间:2014-05-12 15:47:17

标签: python csv dictionary

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

这就是我的字典的样子:

dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[key3]=[7,8,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个密钥的字典。

6 个答案:

答案 0 :(得分:28)

如果您不关心列的顺序(因为字典是无序的),您只需使用zip()

d = {"key1": [1,2,3], "key2": [4,5,6], "key3": [7,8,9]}
with open("test.csv", "wb") as outfile:
   writer = csv.writer(outfile)
   writer.writerow(d.keys())
   writer.writerows(zip(*d.values()))

结果:

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

如果您关心订单,则需要对键进行排序:

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]))

结果:

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

答案 1 :(得分:1)

鉴于

dict = {}
dict['key1']=[1,2,3]
dict['key2']=[4,5,6]
dict['key3']=[7,8,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
key1  key2  key3
1     4     7
2     5     8
3     6     9

答案 2 :(得分:1)

在没有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))

答案 3 :(得分:0)

key_list = my_dict.keys()    
limit = len(my_dict[key_list[0]])    

for index in range(limit):    
  writefile.writerow([my_dict[x][index] for x in key_list])

答案 4 :(得分:0)

保存:

with open(path, 'a') as csv_file:
    writer = csv.writer(csv_file)
    for key, value in dict_.items():
        writer.writerow([key, ','.join(value)])
csv_file.close()        
print ('saving is complete') 

回读:

with open(csv_path, 'rb') as csv_file:
    reader = csv.reader(csv_file);
    temp_dict = dict(reader);
mydict={k:v.split(',') for k,v in temp_dict.items()}    
csv_file.close()
return mydict 

答案 5 :(得分:0)

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

    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)