Read CSV file to dictionairy

Viewed 523

I have created a dictionairy to store my results in. My code stores them in this dictionairy and saves this to an CSV file. However, when I try to read this CSV file I only seem to be able to read it as a DataFrame. But my code does not work with DataFrame, I need the CSV file in 'dictionairy' format.

So I have to be able to either download the CSV file directly as a dict

OR

change the DataFramefile to a dict file.

To clarify:

This is what the Dict looks like when I create it, just a simple string as key input and a value assigned to it:

Dict{String,Any} with 2 entries:
"0.1_10_8" => 13.2
"0.1_10_4" => 6.6

Then I write it to CSV format and it looks like this when I re-load it as DataFrame.

enter image description here

I need to have it the same as before I wrote it as CSV, just like the dictionairy I had before.

2 Answers

Extending @Bogumil example.

If your CSV file has a form

key, value
A, 1
B, 10
C, 15

then you can just do

julia> using CSV

julia> CSV.File("example.csv") |> Dict
Dict{String, Int64} with 3 entries:
  "B" => 10
  "A" => 1
  "C" => 15

By the way, it works other direction too

julia> d = Dict("a" => 1, "b" => 2, "c" => 3)
julia> CSV.write("dict.csv", d)
sh> cat dict.csv
first,second
c,3
b,2
a,1

This is a way to convert DataFrame to a Dict:

julia> using DataFrames

julia> df = DataFrame(rand(2,3), :auto)
2×3 DataFrame
 Row │ x1         x2         x3
     │ Float64    Float64    Float64
─────┼────────────────────────────────
   1 │ 0.872404   0.90496    0.675698
   2 │ 0.0819708  0.0460276  0.814274

julia> Dict(pairs(eachcol(df)))
Dict{Symbol,AbstractArray{T,1} where T} with 3 entries:
  :x2 => [0.90496, 0.0460276]
  :x3 => [0.675698, 0.814274]
  :x1 => [0.872404, 0.0819708]

and here is an example how you can read in CSV-file to a Dict without using DataFrames.jl:

julia> using CSV, Tables

julia> CSV.write("test.txt", df) # I use df created above
"test.txt"

julia> CSV.File("test.txt") |> Tables.columntable |> pairs |> Dict
Dict{Symbol,Array{Float64,1}} with 3 entries:
  :x2 => [0.90496, 0.0460276]
  :x3 => [0.675698, 0.814274]
  :x1 => [0.872404, 0.0819708]
Related