Custom NamedTuple dynamic creation

Hello guys, wondering if there’s a way of dynamically assign keys to a NamedTuple something like this:

 function create_named_tuple(x, y, z)
  mynames = (:position, :y, :z)
  mydata = (x, "free","get")
  return NamedTuple{mynames}(mydata)
 end

Written this way it doesn’t work the keys are literal string “y” and “z” instead of variables passed to the function. Is there a way of doing this without using additional libraries?

see if this helps you


julia> f(y)=(;Symbol(y)=>"ypsilon",)
f (generic function with 1 method)

julia> c='c'
'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)

julia> f(c)
(c = "ypsilon",)


julia> c='z'
'z': ASCII/Unicode U+007A (category Ll: Letter, lowercase)

julia> f(c)
(z = "ypsilon",)



julia> NamedTuple{(Symbol(c),)}(("ypsilon",))
(z = "ypsilon",)

You could write:

function create_named_tuple(x, y, z)
    mynames = (:position, Symbol(y), Symbol(z))
    mydata = (x, "free", "get")
    return NamedTuple{mynames}(mydata)
end

create_named_tuple("paid", "cost", "task")

Note that using dynamic keys like this may limit type stability and reduce performance in some situations. NamedTuple is designed with the idea that keys are usually known at compile time. You should consider whether Dict (which does not “compile in” they keys) is suitable for your use case.

1 Like

Magic! Thanks. However I will take note of mikemoore remark (below) but my use case shouldn’t be so exigent on performance.

Hang on, are the y and z arguments not assigned to symbols to begin with? NamedTuples can only take symbols so why not constrain y::Symbol and z::Symbol? Symbol(y) is flexible but not everything should be forced into a symbol. A Dict wouldn’t need to do that to its keys.