I'm curious as to how OrderedDict from the collections library keeps key/pair order? I looked around online and couldn't find an answer.
1 Answer
From the source code, it appears to be implemented as a dict with a doubly linked list of keys for ordering, as well as another dict that maps keys to their position in the list.
- Insertion just adds to the end of the list.
- Deletion uses the second dict to remove an element from the list.
- Iteration iterates over the linked list.
1 Comment
tyleax
I guess there's a bit more overhead when using OrderedDict than from the normal dict.
dictin Python 3.6 is also ordered, but it's much more efficient.