6

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.

3
  • 10
    github.com/python/cpython/blob/… Commented Mar 1, 2018 at 1:14
  • Thanks, this helps a lot. Commented Mar 1, 2018 at 1:20
  • The standard dict in Python 3.6 is also ordered, but it's much more efficient. Commented Mar 1, 2018 at 3:47

1 Answer 1

8

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.
Sign up to request clarification or add additional context in comments.

1 Comment

I guess there's a bit more overhead when using OrderedDict than from the normal dict.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.