xiaodai
xiaodai

Reputation: 16004

Julia: How to obtain the names of a NamedTuple?

For example,

nt = (a=1,b="b",c=5.0)

How do I get the names of nt which are [:a,:b,:c]?

Upvotes: 4

Views: 3014

Answers (2)

Jeffrey Sarnoff
Jeffrey Sarnoff

Reputation: 1757

Note that the names are Julia symbols (that's what the leading colon signifies). If you want the names to be strings rather than symbols, construct the strings from the collected keys.

 julia> nt = (two = 2, three = 3)
 (two = 2, three = 3)

 julia> namestrs = String.collect(keys(nt))
 2-element Array(String,1):
  "two"
  "three"

Upvotes: 3

carstenbauer
carstenbauer

Reputation: 10127

As for any other key-value structure (like a dictionary), you can use the keys function:

julia> nt = (a=1,b="b",c=5.0)
(a = 1, b = "b", c = 5.0)

julia> keys(nt)
(:a, :b, :c)

Note that in general this returns an iterator over the keys. If you really want to materialize it collect the result:

julia> collect(keys(nt))
3-element Array{Symbol,1}:
 :a
 :b
 :c

Upvotes: 7

Related Questions