Does anyone else find the behavior of `Dict(::NamedTuple)` a little funky:```juli

does anyone else find the behavior of Dict(::NamedTuple) a little funky:

julia> kw  = (default_u0 = [0., 0., 0.], default_p=[0., 0., 0.])
(default_u0 = [0.0, 0.0, 0.0], default_p = [0.0, 0.0, 0.0])

julia> kwd  = Dict(kw)
Dict{Float64, Float64} with 1 entry:
  0.0 => 0.0

doesn’t it make way more sense to do Dict(keys(kw) .=> values(kw))?

Note that the original poster on Slack cannot see your response here on Discourse. Consider transcribing the appropriate answer back to Slack, or pinging the poster here on Discourse so they can follow this thread.
(Original message :slack:) (More Info)

I think you’re looking for Dict(pairs(kw)). Here’s the explanation: Dict expects an iterable of key, value pairs, but it’s not picky about whether it’s an actual Pair. This demo may explain it:

julia> t = (a = [1, 2, 3], b = [4, 5, 6])
(a = [1, 2, 3], b = [4, 5, 6])

julia> for item in t    # iteration over tuples (named or not) returns the *values*
           @show item
       end
item = [1, 2, 3]
item = [4, 5, 6]

julia> Dict(t)    # the Dict constructor accepts any iterable that returns items supporting `item[1], item[2]`
Dict{Int64, Int64} with 2 entries:
  4 => 5
  1 => 2

julia> for item in pairs(t)     # this iterates over key=>value pairs
           @show item
       end
item = :a => [1, 2, 3]
item = :b => [4, 5, 6]

julia> Dict(pairs(t))
Dict{Symbol, Vector{Int64}} with 2 entries:
  :a => [1, 2, 3]
  :b => [4, 5, 6]

However, I agree that there is room for confusion here. I’ve filed an issue to consider this topic when we get a chance to consider breaking changes: Less quacking in Dict constructor? · Issue #39848 · JuliaLang/julia · GitHub

5 Likes