最好的事情是,你可以查看OrderedDict
的源代码来更好地理解它。
实际上,它是用纯Python实现的!这意味着你可以复制它,重新定义它,甚至无节制地变异它,直到你理解为止。
它确实使用了双向链表,这在源文件的docstring中有说明。通过理解双向 链表的工作原理并浏览源代码,你将会对它的工作方式有很好的掌握:
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries.
# The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three: [PREV, NEXT, KEY].