logo

Julia's Named Tuples 📂Julia

Julia's Named Tuples

Overview

Named tuples are tuples that, unlike regular tuples, can be used like dictionaries or structures. They have an array of symbols as keys and allow access to values via those keys, all the while retaining their tuple-like usage.

Code

x = rand(Bool, 5); y = rand(Bool, 5);

z = (; x, y)
typeof(z)

z.x

Let’s run the above code to see how named tuples are used.

julia> z = (; x, y)
(x = Bool[0, 0, 1, 1, 0], y = Bool[1, 1, 0, 0, 0])

julia> typeof(z)
NamedTuple{(:x, :y), Tuple{Vector{Bool}, Vector{Bool}}}

A simple way to create a named tuple is to just make a tuple and put a semicolon ; right after the opening parenthesis. For instance, (; x) is equivalent to (; x=x).

julia> z.x
5-element Vector{Bool}:
 0
 0
 1
 1
 0

julia> z[2]
5-element Vector{Bool}:
 1
 1
 0
 0
 0

Named tuples can be accessed by the name of their symbols, as well as by their index.

Environment

  • OS: Windows
  • julia: v1.6.3