Hi Julia users,
I was trying to extract multiple elements from a NamedTuple and Failed.
It works for extracting one element (pt here is a NamedTuple) through the following code line
pt[:cancer_type]
But doesn’t work for extracting multiple elements, see below
pt[:cancer_type, :time_to_cancer_dx]
or
pt[[:cancer_type, :time_to_cancer_dx]]
Any suggestions? Thanks a lot.
obj = (a = 1, b = 2, c = 3)
a, b, c = obj.a, obj.b, obj.c
a, b, c = [ getproperty(obj, pn) for pn in propertynames(obj) ]
or using Parameters.jl
using Parameters
@unpack a, b, c = obj
Use three back-ticks (`) for formatting code in posts.
Or something like
julia> nt = (a = 1, b = 2, c = 3)
(a = 1, b = 2, c = 3)
julia> getproperty.(Ref(nt), [:a, :b])
2-element Array{Int64,1}:
1
2
but note that a NamedTuple
may not be the best match for this use case (you don’t get the inference advantages when the field names are provided dynamically, you might as well just use a Dict
or similar).