Julia convert NamedTuple to Dict
Asked Answered
S

1

8

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?

Subplot answered 28/10, 2021 at 14:17 Comment(0)
L
10

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
Lethalethal answered 28/10, 2021 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.