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

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 Likes

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

Cheers!
Kevin

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

1 Like

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.

2 Likes

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

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.