1

I would like to write a simple dict to CSV for later reuse in a Pythonic manner.

The approaches I have found online do not seem elegant and Pythonic to me, so I am looking for a better solution. For example:

How do I write a Python dictionary to a csv file?

How to export dictionary as CSV using Python?

dic = {1:"a",
       2:"b",
       3:"c"}

Output:

1,a
2,b
3,c
max
  • 4,141
  • 5
  • 26
  • 55

4 Answers4

1

The Q&As you're refering to are different. They're assuming that the keys are the first row / the same for all data (hence the advice of using DictWriter)

Here, your dictionary is considered as a list of key/value pairs, and it's not ordered, so if order matters, just sort it according to the elements (which only considers keys since they're unique).

import csv

dic = {1:"a",
       2:"b",
       3:"c"}

with open("out.csv","w",newline="") as f:  # python 2: open("out.csv","wb")
    cw = csv.writer(f)  # default separator is ",", no need for more params
    cw.writerows(sorted(dic.items()))

this approach is very fast because you're not accessing the values by key (no need), stable (the output is the same everytime thanks to the sort function), and uses no loop thanks to csv.writerows. If the order doesn't matter, replace the last line by:

    cw.writerows(dic.items())

csv module automatically converts items to strings when writing so it's not an issue when the data type is integer like in your example.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

you can do easily with pandas,

 import pandas as pd
 df=pd.DataFrame(sorted(dic.items()))
 df.to_csv("your_file.csv",index=False)
Pyd
  • 6,017
  • 18
  • 52
  • 109
0

Try this:

  import csv
    dic = {1:"a",
           2:"b",
           3:"c"}
    with open('output.csv', 'wb') as f:
        writer = csv.writer(f)
        for key in dic:
            writer.writerow([key, dic[key]])
mickNeill
  • 346
  • 5
  • 22
0

Maybe a more pythonic way:

with open('dic.csv', 'wb') as csv_file:
    csv.writer(csv_file).writerows(dic.items())
Austin
  • 25,759
  • 4
  • 25
  • 48