Write dictionary of lists to a CSV file
If you don't care about the order of your columns (since dictionaries are unordered), you can simply use 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:
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:
key1 key2 key3
1 4 7
2 5 8
3 6 9
Roll your own without the csv module:
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))