How to loop over the key/value pairs of a NamedTuple?

question

#1

I tried the following without success:

using NamedTuples

nt = @NT(a=1, b=1.0)

for (k,v) in nt
  println(k, " => ", v)
end

#2

Try something like

for (k,v) in zip(keys(nt), nt)
    println(k, " => ", v)
end

Note that NamedTuples behave like tuples in many contexts, and when you iterate over them you just get the values.


#3

Thank you @Tamas_Papp, I was wondering if another method existed, it seems like a common pattern for named tuples.


#4

However, I am not sure if it is type stable, zip sometimes isn’t. YMMV, and you could also use map.


#5

I opened an issue to see if someone has more ideas:

Is the solution with zip guaranteed to always match the pairs in the named tuple?


#6

I think @Tamas_Papp’s recommendation is the right one and I don’t think there is another way of doing this. It might be nice to add a pairs functions to the package that returns a Pair iterator.

Tamas is also right about type stability, that for loop won’t be type stable. If you use map instead, you should get a type stable version instead.


#7

@davidanthoff I am using @Tamas_Papp’s solution, thanks.

I still have an issue with using NamedTuple objects as described in this post though:

Basically, I am trying to have an outer constructor with NamedTuples that get converted into an inner constructor with dictionaries. My attempt failed.