Select multiple fields from a NamedTuple and create new NamedTuple

Hello, I wonder how I can take several fields of an NamedTuple and generate a new NamedTuple from them.

I mean, the generator way is clear

A = (a = 1, b = 2, c = 3)
args = (:a, :b)
B = NamedTuple{args}(getfield(A, i) for i in args)

but I wonder if it can be done simpler.

Maybe even something like this A.(a,b) would be cool :wink:

Maybe just this:

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

julia> B = (a=A.a, b=A.b)
(a = 1, b = 2)

Yeah, for two or three fields it is shorter, but I have something around 10 fields in my original code and i also I have to specify the new names on my own and cannot use a Tuple of names.

Probably the generator version is the shortest is this case but perhaps someone knows a trick I am not aware ofโ€ฆ

You can do

julia> Base.getindex(A::NamedTuple, args::Tuple) = NamedTuple{args}(getfield(A, i) for i in args)

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

with the risk that base Julia at some future point introduces a conflicting method for that type signature.

1 Like

Hey, that is cool. Why not just put it into Base, :wink:

Thanks

1 Like

A preemptive PR could take care of that :wink:

I looked into the implementation, and what you want is already implemented in Base:

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

julia> NamedTuple{(:a,:b)}(A)
(a = 1, b = 2)
4 Likes

Thanks, I thought, that I have tried this version but it seams, I was doing something wrong :wink: Works pretty well.