I know Python dicts are unordered, but if you call iteritems(), it returns a list, which is ordered. How is the ordering of that list determined?
Asked
Active
Viewed 6,655 times
3
-
Implementation-dependent, I'd guess. What are you using? CPython? – Kevin Apr 15 '14 at 19:25
-
The same way it's determined in `list(d)`, `for k in d:`, `for v in d.values()`, etc.: arbitrarily. – Apr 15 '14 at 19:26
-
By definition the order of the dictionary itself is undefined and `iteritems()` doesn't perform any sorting. There is a `sorteddict()` if you need it – Basic Apr 15 '14 at 19:27
-
The idea is that you can't/shouldn't know how it's determined, because you can't rely on it being determined that way in the future. – BrenBarn Apr 15 '14 at 19:34
-
Also, iteritems() returns an iterable, which is technically different from a list. However, you can call list(iterableValue) to get a list value. – Al Sweigart Apr 15 '14 at 19:59
1 Answers
8
The order is determined by the order they appear in the dict's internal table. Which is essentially the hash of the object mod the length of that table (plus some offset when there are hash collisions). The order will change anytime the size of the internal table changes, which can happen anytime you add an item (or less often when you remove items) from the dict.
You cannot reasonably predict it, and shouldn't rely on dictionary ordering for any purpose.
Read this:

joshua
- 2,509
- 17
- 19