Empty Named Tuple

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?


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 keys are Symbols, you can do


You can’t mutate named tuples in-place. Some idioms that can be helpful here:

julia> a = NamedTuple()

julia> a = (;)  # doesn't work in old Julia releases

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.