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?




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

help?> enumerate
search: enumerate Enumerate


  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.


If d is a Dict, you can just do

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

to iterate over keys and values.


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


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


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:



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