Michael Paul
Michael Paul

Reputation: 157

In Julia 1.0, how to set a named tuple with only one key value pair?

When I run

t = (one = "one", two = 2) typeof(t)

in REPL, I get

NamedTuple{(:one, :two),Tuple{String,Int64}}

but when I run

t = (one = "one") typeof(t)

I get String as type.

Is it possible to set a named tuple with just one named value so that I can access for example t[1] as well as t.one and get "one" returned?

Upvotes: 4

Views: 734

Answers (1)

carstenbauer
carstenbauer

Reputation: 10127

Put a comma, i.e.

julia> t = (one = "one",)
(one = "one",)

julia> typeof(t)
NamedTuple{(:one,),Tuple{String}}

The reason why t = (one = "one") doesn't work is because it's equivalent to t = one = "one". So you are defining two variables both with value "one".

julia> t = (one = "one")
"one"

julia> typeof(t)
String

julia> typeof(one)
String

Upvotes: 5

Related Questions