How do I save my dictionary as a .csv (or excel) file?

I have a dictionary, which I want to save to an excel or csv file with keys in one column and the entries in another. The keys are strings and the entries are float64s. I thought about converting my dictionary to a DataFrame but I am not sure if this type is supported in Julia or how to convert if it is, or even how to save a dataframe as csv. Can dictionaries be saved as csv files directly?


This is easily done with the CSV package (If you don’t have it, run Pkg.add(“CSV”) in your REPL)

using CSV
test = Dict("a"=>1, "b"=>2, "c"=>3)
CSV.write("test.csv", test)

You can add a file-path like this: “/Users/your/custom/location/test.csv”

If you want to save in .xlsx:

using XLSX
x      = Dict("a"=>1.0, "b" => 2.0)  
fid    = XLSX.openxlsx("df.xlsx", mode="w")
header = ["keys";"values"]
data   = [[collect(keys(x))];[collect(values(x))]]

XLSX.writetable("df.xlsx", data,header)

Thanks, that works. Is there a way to specify headers? I tried CSV.write("File.csv",VariableName,["Column1Name";"Column2Name]) but I got a Method error.

Thanks! I think csv would be most convenient however. That being said the header argument you have specified doesn’t seem to work for csv.write :frowning:

The example is only for Excel files and it’s using the XLSX package.
If you want to use CSV to write .csv files as in @TheLateKronos example, you could define your header as a comma delimited string, write that line to csv, and then write your test dictionary.

It seems you can specify custom column names when reading CSV’s, but I also just get the same error when I try to specify a vector of strings as column names. The best I can think of is to have the keyword argument append=true, which makes it so that column names are not written. Then you can add them yourself manually.

Alternatively find a way to write it to a dataframe with the column names you want, and save that