'How to iterate over names and values in Julia NamedTuple?

E.g. if I have:

t = (
  a = 1:5,
  b = 2:6,
  c = 3:7,
)

And I'd like:

(
  a = 15,
  b = 20,
  c = 25,
)

What's an idiomatic way to accomplish this?



Solution 1:[1]

I guess you want

julia> map(sum, t)
(a = 15, b = 20, c = 25)

Solution 2:[2]

i don't know how to pass from 1:5 to 15, but if you allow me to invent such function, then, you could do:

julia> NamedTuple(k=>length(v)*(first(v)+2) for (k,v) in pairs(t))
(a = 15, b = 20, c = 25)

Solution 3:[3]

You can also use good old map:

julia> map(x -> length(x) * (first(x) + 2), t)
(a = 15, b = 20, c = 25)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DNF
Solution 2 longemen3000
Solution 3 Andrej Oskin