10 Julia Recipes You Can't Miss

julia> abc = (a=1, b="hello", c = 3.14)
(a = 1, b = "hello", c = 3.14)
julia> ac = NamedTuple{(:a, :c)}(abc)
(a = 1, c = 3.14)
"""
    keepkeys(nt::NamedTuple, syms::Tuple{Vararg{Symbol}})

Construct a subset of `nt` using only the keys in `syms`.
""" keepkeys

julia> keepkeys(nt::NamedTuple, ks=NTuple{N,Symbol} where {N}) =
                 NamedTuple{ks}(nt)

julia> b = keepkeys(abc, (:b,))
(b = "hello",)

julia> bc = keepkeys(abc, (:b, :c))
(b = "hello", c = 3.14)

julia> keepkeys(abc, (:z,))
ERROR: type NamedTuple has no field z
"""
    omitkeys(nt::NamedTuple, syms::Tuple{Vararg{Symbol}})

Construct a subset of `nt` omitting the keys in `syms`.
""" omitkeys

julia>  omitkeys(nt::NamedTuple, ks=NTuple{N,Symbol} where {N}) =
                  keepkeys(nt, Tuple(setdiff(keys(nt), ks)))

julia> bc = omitkeys(abc, (:a,))
(b = "hello", c = 3.14)

julia> b = omitkeys(abc, (:a, :c))
(b = "hello",)

julia> abc2 = omitkeys(abc, (:z,))
(a = 1, b = "hello", c = 3.14)
3 Likes