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.