Convert dictionary to Tables.table

I have a dictionary where the values are a named tuple:

julia> d = Dict("x" => (a = 1, b = 2), "y" => (a = 3, b = 4))
Dict{String,NamedTuple{(:a, :b),Tuple{Int64,Int64}}} with 2 entries:
  "x" => (a = 1, b = 2)
  "y" => (a = 3, b = 4)

How can I convert that to a Tables.table? Needless to say, Iā€™d need to specify the name of the first column, the one expressed by the keys of the dictionary, while the other columns will be named after the names of the fields of the named tuple.

To be honest, while it would be great to know that, my ultimate goal is to save d as a CSV file (which is easy to do once I have the table).


This works:

function totable(d::Dict{R, NamedTuple{S,T}}, firstname::Symbol) where {R,S,T}
    names = [firstname, S...]
    renamecol(table(d), [i => name for (i, name) in enumerate(names)])

The easier is probably to convert it to something that iterates named tuples:

itr = (merge((; key = key), val) for (key, val) in d)
itr |> CSV.write("test.csv")
1 Like

Just another option from @joshday (via slack):

 renamecol(table(d), [1=>:key, 2=>:a, 3=>:b])

Here is the Queryverse variant of this:

using Query, CSVFiles

d |> @map({key=_[1], _[2]...}) |> save("foo.csv")

Or you can pipe it into a DataFrame or some other table type.

1 Like