Home > database >  Julia convert NamedTuple to Dict
Julia convert NamedTuple to Dict

Time:10-29

I would like to convert a NamedTuple to a Dict in Julia. Say I have the following NamedTuple:

julia> namedTuple = (a=1, b=2, c=3)
(a = 1, b = 2, c = 3)

I want the following:

julia> Dict(zip(keys(namedTuple), namedTuple))
Dict{Symbol, Int64} with 3 entries:
  :a => 1
  :b => 2
  :c => 3

This works, however I would've hoped for a somewhat simpler solution - something like

julia> Dict(namedTuple)
ERROR: ArgumentError: Dict(kv): kv needs to be an iterator of tuples or pairs

would have been nice. Is there such a solution?

CodePudding user response:

The simplest way to get an iterator of names and values is pairs:

julia> Dict(pairs(namedTuple))
Dict{Symbol, Int64} with 3 entries:
  :a => 1
  :b => 2
  :c => 3
  • Related