Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write dictionary of lists to a CSV file

I'm struggling with writing a dictionary of lists to a .csv file.

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:

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. e.g.:

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.

like image 584
suschi Avatar asked May 12 '14 15:05

suschi


People also ask

How do I convert a dictionary to a csv file?

Easiest way is to open a csv file in 'w' mode with the help of open() function and write key value pair in comma separated form. The csv module contains DictWriter method that requires name of csv file to write and a list object containing field names.

How do I convert a list into a csv file in Python?

To convert the list to csv, we need to convert from list to dataframe and then use the to_csv() function to convert dataframe to a csv file. In this example, we have first imported pandas library and then define the four lists and map it with its column using a dictionary.


1 Answers

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 
like image 84
Tim Pietzcker Avatar answered Sep 24 '22 23:09

Tim Pietzcker