Is it possible to initialize an empty NamedTuple with the appropriate keys and types for values? Can you then push future NamedTuples into this empty NamedTuple?
Thanks!
Is it possible to initialize an empty NamedTuple with the appropriate keys and types for values? Can you then push future NamedTuples into this empty NamedTuple?
Thanks!
Nope. part of the reasons named tuples are so useful is that they are immutable. You probably want to use a Dict
if this is your use case. the package NamedTupleTools might have something you are interested in.
If you have a Dict
d
where all the key
s are Symbol
s, you can do
NamedTuple{Tuple(keys(d))}(Tuple(values(d)))
You can’t mutate named tuples in-place. Some idioms that can be helpful here:
julia> a = NamedTuple()
NamedTuple()
julia> a = (;) # doesn't work in old Julia releases
NamedTuple()
julia> a = merge(a, (x=1,))
(x = 1,)
julia> a = (; a..., y=2)
(x = 1, y = 2)
julia> a = (; a..., :z => 3)
(x = 1, y = 2, z = 3)
julia> d = Dict(:aaa => 1, :bbb => 2, :ccc => 3);
julia> (; d...)
(bbb = 2, ccc = 3, aaa = 1)
Thanks. I am trying to learn how to utilize tuples for performance.
Thanks this was helpful.