Accessing dictionary items by position in Python 3.6+ efficiently

For an OrderedDict it’s inherently O(n) because the ordering is recorded in a linked list.

For the builtin dict, there’s a vector (a contiguous array) rather than a linked list, but pretty much the same thing in the end: the vector contains a few kind of “dummies”, special internal values that mean “no key has been stored here yet” or “a key used to be stored here but no longer”. That makes, e.g., deleting a key extremely cheap (just overwrite the key with a dummy value).

But without adding auxiliary data structures on top of that, there’s no way to skip over the dummies without marching over them one at a time. Because Python uses a form of open addressing for collision resolution, and keeps the load factor under 2/3, at least a third of the vector’s entries are dummies. the_vector[i] can be accessed in O(1) time, but really has no predictable relation to the i’th non-dummy entry.

Leave a Comment