5

I have a dictionary like {a: [1, 2, 3], b: [4, 5, 6], c: [7, 3, 2]} and I would like to write this to a csv file in Python. I was the csv file as:

col1,col2,col3,col4
a,1,2,3
b,4,5,6
c,7,3,2

I tried using CSV Dict writer but I could not get as value is a list here.

Any help is appreciated!

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
Cool Geek
  • 79
  • 2
  • 7
  • do you mean `{'a':[1,2,3],...}` ? or is `a` really unquoted? – Joran Beasley Mar 23 '16 at 19:02
  • 1
    Well, a ***.csv** file is just a text file. You can just try iterating through a dictionary and building a string. Later on, just write this string to the file using `open()` function. Your string should look like: `col1;col2\n 1;4\n 2;5\n 3;6\n` – Laszlowaty Mar 23 '16 at 19:03
  • try `pandas` `DataFrame.from_csv`: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_csv.html – n1c9 Mar 23 '16 at 19:04
  • @JoranBeasley yes it is a string. it should be like {'a':[1,2,3]}.But I want this key and list of values to be in a single row in different columns – Cool Geek Mar 23 '16 at 19:05

6 Answers6

5

You can use Python's csv library for doing this as follows (for Python 3.x see below):

import csv

my_dict = {"a" : [1, 2, 3], "b" : [4, 5, 6], "c" : [7, 3, 2]}

with open("output.csv", "wb") as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(['col1', 'col2', 'col3', 'col4'])
    
    for key in sorted(my_dict.keys()):
        csv_output.writerow([key] + my_dict[key])

Giving you:

col1,col2,col3,col4
a,1,2,3
b,4,5,6
c,7,3,2

The .writerow() function takes a list of items and writes them correctly formatted to your output CSV file. As you want the key as the first item, it passes the key concatenated with them items found when looking the key up in the my_dict dictionary, thus resulting in the output that you wanted.


Note: If Python 3.x is used, the file open line would need to be modified, and sorting would not be required:

with open("output.csv", "w", newline="") as f_output:
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
0
with open("out.csv","wb") as csv_out:
    # first the header
    csv_out.write(",".join("Col%d"%i for i in range(len(a_dict.values()[0]))+"\n")
    # then each row .... make sure its sorted by the keys ...
    for key,a_list in sorted(a_dict.items(),key=lambda row:row[0])
        x = [key,]
        x.extend(a_list)
        csv_out.write(",".join(str(i) for i in x)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

Hope following code can help:

fo = open("example.csv", "wr")
fo.write("col1,col2,col3,col4\n")
fo.write("a,1,2,3\n")
fo.write("b,4,5,6\n")
fo.write("c,7,8,9\n")
fo.close()
Yi Chen
  • 1
  • 4
0
>>> mydict
{'b': [4, 5, 6], 'c': [7, 3, 2], 'a': [1, 2, 3]}
>>> result ="\n".join(["{0} {1}".format(key, " ".join([str(x) for x in list_value])) for key, list_value in mydict.iteritems()])
>>> print result
b 4 5 6
c 7 3 2
a 1 2 3

Writes result into a csv file.

If the order matters, you can use OrderedDict

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
0
d={'a': [1, 2, 3],'b': [4, 5, 6], 'c': [7, 3, 2]}
with open("result.txt","w+") as f:
    for k,v in d.items():
            alist=[k]+[str(r) for r in v]#alist=['a','1','2','3']
            line=' '.join(alist)+"\n"#line="a  1 2 3\n"
            f.write(line)
python必须死
  • 999
  • 10
  • 12
0

Just for practice, here's another version;

mydict = {'a': [1, 2, 3], 'c': [7, 3, 2], 'b': [4, 5, 6]}

with open('test.csv','w') as f:
  for k,v in mydict.iteritems():
    f.write(str.join(',', [k]+[str(i) for i in v])+'\n')

It just loops though the dictionary items, generating a row for each.

Each row is generated by creating an array with the key as first element with the values converted to strings following. It then just joins the elements of the array using a comma separator.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294