[英]Write dictionary of lists to a CSV file
I'm struggling with writing a dictionary of lists to a .csv file. 我正在努力将列表字典写入.csv文件。
This is how my dictionary looks like: 这是我的字典的样子:
dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[key3]=[7,8,9]
I want the .csv file to look like: 我希望.csv文件看起来像:
key1 key2 key3
1 4 7
2 5 8
3 6 9
At first I write the header: 首先,我写标题:
outputfile = open (file.csv,'wb')
writefile = csv.writer (outputfile)
writefile.writerow(dict.keys())
So far so good... However, my problem is that I don't know how I could assign one list to the corresponding column. 到目前为止很好...但是,我的问题是我不知道如何将一个列表分配给相应的列。 eg:
例如:
for i in range(0,len(dict[key1])):
writefile.writerow([dict[key1][i],dict[key2][i],dict[key3][i])
will randomly fill the columns. 将随机填充列。 Another problem is, that I have to manually fill in the keys and can't use it for another dictionary with 4 keys.
另一个问题是,我必须手动填写键,并且不能将其用于具有4个键的另一本词典。
If you don't care about the order of your columns (since dictionaries are unordered), you can simply use zip()
: 如果您不关心列的顺序(因为字典是无序的),则可以简单地使用
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()))
Result: 结果:
key3 key2 key1
7 4 1
8 5 2
9 6 3
If you do care about order, you need to sort the keys: 如果您确实关心订单,则需要对键进行排序:
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]))
Result: 结果:
key1 key2 key3
1 4 7
2 5 8
3 6 9
This will work even when the list in key are of different length. 即使键中的列表长度不同,这也将起作用。
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)
You can use pandas for saving it into csv: 您可以使用熊猫将其保存到csv中:
df = pd.DataFrame({key: pd.Series(value) for key, value in dictmap.items()})
df.to_csv(filename, encoding='utf-8', index=False)
Given 给定
dict = {}
dict['key1']=[1,2,3]
dict['key2']=[4,5,6]
dict['key3']=[7,8,9]
The following code: 如下代码:
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')
produces a csv that looks like: 产生如下的csv:
key1 key2 key3
1 4 7
2 5 8
3 6 9
Roll your own without the csv module: 在没有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))
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])
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.