MetaColon
MetaColon

Reputation: 2871

Julia convert NamedTuple to Dict

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?

Upvotes: 9

Views: 1363

Answers (1)

phipsgabler
phipsgabler

Reputation: 20950

The simplest way to get an iterator of keys and values for any key-value collection is pairs:

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

Upvotes: 11

Related Questions