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

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 Likes

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.

4 Likes

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

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

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

https://github.com/blackrock/NamedTuples.jl/issues/42

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

1 Like

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.

2 Likes

@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.

1 Like

What’s the current best way for iterating key/value pairs of a NamedTuple? pairs doesn’t work:

julia> for v in (a=1, b=2) println(v) end
1
2

julia> for (k,v) in pairs(a=1, b=2) println(v) end
ERROR: MethodError: no method matching pairs(; a=1, b=2)
Closest candidates are:
  pairs(::AbstractDict) at ~/julia/julia-1.7.2/share/julia/base/abstractdict.jl:140 got unsupported keyword arguments "a", "b"
  pairs(::IndexLinear, ::AbstractArray) at ~/julia/julia-1.7.2/share/julia/base/iterators.jl:226 got unsupported keyword arguments "a", "b"
  pairs(::IndexCartesian, ::AbstractArray) at ~/julia/julia-1.7.2/share/julia/base/iterators.jl:227 got unsupported keyword arguments "a", "b"
  ...
Stacktrace:
 [1] top-level scope
   @ ./REPL[14]:1
1 Like

Actually I was doing a stupid mistake, pairs works:

julia> for (k,v) in pairs((a=1, b=2)) println(k => v) end
:a => 1
:b => 2
1 Like