Is order well-defined for multiple iterations over `Dict`?

question

#1

If I iterate over (key,value) pairs in Dict, or keys(dict), or values(dict), using multiple iterations, but not modifying the dict between iterations, is it guaranteed that I get the objects in the same order? (which is “random”, but I don’t care as long as it is consistent).

Looking at the implementation, this seems to be so, but I don’t know if this is something I can rely on (could not find it in the documentation).


#2

Yes. The underlying storage arrays are only resized/rehashed when the contents of the Dict itself are modified.

Cheers!
Kevin


#3

But that’s actually an implementation detail of Dict, and not necessarily guaranteed in the future, IIUC.
But see https://github.com/JuliaLang/julia/issues/20678


#4

Probably the best method (at least semantically) would be to convert the Dict into an OrderedDict (from DataStructures), this would freeze the order for later usage.


#5

That’s what I thought. It would be nice to have that guarantee though, perhaps as a trait for some types.


#6

Since I am only using it a few times, and always linearly after I finished accumulating values, it turns out that collecting and working on that is the fastest solution.