Get multiple elements from named tuples

Why does the following not work for named tuples?

x = (a=1, b=2, c=3)
x[1:2]
x[[1,2]]

With unnamed tuples like x = (1, 2, 3) it works fine. Tested with Julia 1.8.2.

1 Like

My initial reaction is that named tuples are indexed by name, not by index, so x[1:2] doesn’t make sense. But we do allow indexing into a named tuple by a single index:

julia> x = (a=1, b=2, c=3)
(a = 1, b = 2, c = 3)

julia> x[1]
1

so I agree it’s surprising that we don’t allow you to supply multiple indices.

2 Likes

Good point. x[[:a, :b]] works. I guess my expectations are inherited from two decades with R where one can use both types of indexing, at least for lists, arrays and data frames.

The keys and values from named tuple x are accessible separately with such indexing:

values(x)[1:2]
keys(x)[1:2]
2 Likes

… and from this

julia> x[keys(x)[1:2]]
(a = 1, b = 2)
2 Likes