Enumerate(dict) behavior

Hi All,

enumerate(iter) behavior enumerates over an index and dataItem to the associated index. For associative containers like Dict one would believe the natural iteration will be over named indexes which is the (key, value). However, we see a iterator over an Int and Pair{K,V}.

Any reason why this has been the approach? Will this behavior change in future?

regards,

Sambit

2 Likes

No it doesn’t. Please read the doc of it.

help?> enumerate
search: enumerate Enumerate

  enumerate(iter)

  An iterator that yields (i, x) where i is a counter starting at 1, and x is the ith value from
  the given iterator. It's useful when you need not only the values x over which you are

So no.

1 Like

If d is a Dict, you can just do

for (k, v) in d
println(k, v)
end

to iterate over keys and values.

4 Likes

This definitely makes sense. Thanks.

This makes me wonder why the syntax for iterating over key-value pairs hasn’t been generalized to other data formats, such as custom types or array of arrays. For example:

m = [rand(10) for i in 1:10]

for (i,v) in m
#do some stuff
end

I’m not sure what you would want i and v to be in that case?

1 Like

Presumably this would be similar to for (i, v) in enumerate(m). It would seem pretty surprising for iterating a vector of values not to yield those values.

Sorry for being unclear. As @StefanKarpinski said, I was thinking that it would function just like enumerate(). So i would be an index and v would be a sub-array. It would have the benefit of being consistent with the syntax of the dictionary iterator and would also be more concise than enummerate().

Unlike dict iteration which is undefined or does different things than iterate key-value pairs in various languages (e.g. in Python, iterating a dict yields the keys), I don’t think there’s any language where iterating a vector of values does anything besides returning those values in order. So that would a truly radical language change. On the other hand, changing dictionaries to yield values and not keys is currently being discussed as a way of conceptually unifying arrays and dictionaries:

https://github.com/JuliaLang/julia/issues/24019

I’m 99% sure that iterating an array in JS returns the indices, which I always find consistently annoy.

It’s also worth noting that v0.7 has the new pairs function, allowing you to iterate dictionaries and arrays alike:

for (i, value) in pairs(x)
    @assert x[i] == value
end
4 Likes