Is there an easy way in base Julia to create a NamedTuple with all the fields except some particular ones? Currently I have the following, but I’m wondering if I’m missing something obvious. I’m calling it delete as it seems to do what delete! does with Dicts, but not in-place.
"""
delete(nt::NamedTuple, fieldnames)
Remove the given fields from `nt`, returning a new `NamedTuple`
"""
function delete(nt::NamedTuple, fieldnames...)
(; filter(p->first(p) ∉ fieldnames, collect(pairs(nt)))...)
end
The collect is necessary because apparently filter on pairs returns a Dict, which loses ordering information.
I naïvely thought that deleting a key-value pair from a NamedTuple is so analogous to doing so from a Dict that delete() is the most appropriate name for this operation. But apparently, it’s not. Why?
I’ve been also surprised that there is no delete() for Dict whereas there is delete!(). I thought it would be nt2 = delete(nt1, keytodelete) for a NamedTuple. . . .
I think I understand the issue. delete!(dict, . . .) works by modifying the first object, but delete!(nt, . . .) cannot, because deleting an element would change the type of the object, which cannot be an in-place modification.