How to make a named tuple from a dictionary?


#1

Is there a simple way to make a named tuple from a Dict{Symbol, T}?


#2

There should be an easier way, but this works:

julia> NamedTuple{tuple(keys(di)...), Tuple{typeof.(collect(values(di)))...,}}((values(di)...,)) 
(a = 1, b = 5.6)```

#3
dictkeys(d::Dict) = (collect(keys(d))...,)
dictvalues(d::Dict) = (collect(values(d))...,)

namedtuple(d::Dict{Symbol,T}) where {T} =
    NamedTuple{dictkeys(d)}(dictvalues(d))

dictionary = Dict(:a => 5, :b => 6, :c => 7)
Dict{Symbol,Int64} with 3 entries:
  :a => 5
  :b => 6
  :c => 7

namedtuple(dictionary)
(a = 5, b = 6, c = 7)

dictionary = Dict(:a => 5, :b => 6.0, :c => "7")
Dict{Symbol,Any} with 3 entries:
  :a => 5
  :b => 6.0
  :c => "7"

namedtuple(dictionary)
(a = 5, b = 6.0, c = "7")

#4

Thanks @mauro3 and @JeffreySarnoff for the replies, it would be nice of you to make a PR!