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).


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



But that’s actually an implementation detail of Dict, and not necessarily guaranteed in the future, IIUC.
But see


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.


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.