Convert Dict to NamedTuple

I’m looking for a clean way to convert Dictionaries into NamedTuples.
I found a helpful topic, however, that solution only works for Dicts with symbol keys.

julia> (; Dict(:a => 5, :b => 6, :c => 7)…)
(a = 5, b = 6, c = 7)

When string keys are converted to symbols, the order reverses.
I found a way to solve this, but I expect there is a more clean and efficient way to do this.
Any suggestion?

My code:

julia> d = Dict(“a” => 5, “b” => 6, “c” => 7)
Dict{String, Int64} with 3 entries:
“c” => 7
“b” => 6
“a” => 5

julia> (; zip(Symbol.(keys(d))[end:-1:begin], [values(d)…][end:-1:begin])…)
(a = 5, b = 6, c = 7)

Dicts do not have order. Any order you see is coincidental.

julia> NamedTuple(Dict(:a=>1, :b=>2))
(a = 1, b = 2)
2 Likes

Thanks for pointing that out.
Than I suspect my solution can be reduced to:

(; zip(Symbol.(keys(d)), values(d))…)

Is this the best way to covert a Dict with string keys to a NamedTuple or is the a cleaner and more efficient way?

This one is at least clearer, in my opinion.

julia> d = Dict("a" => 5, "b" => 6, "c" => 7)
Dict{String, Int64} with 3 entries:
  "c" => 7
  "b" => 6
  "a" => 5

julia> NamedTuple((Symbol(key),value) for (key,value) in d)
(c = 7, b = 6, a = 5)
2 Likes

As a side note, if you do want the keys to be sorted (in insertion order), you can used an OrderedDict or LittleDict from the package OrderedCollections

3 Likes