Python的OrderedDict如何记住插入的元素?
1 个回答
10
这段内容最棒的地方在于,你可以查看OrderedDict
的源代码,来更好地理解它。
其实它也是用纯Python实现的!这意味着你可以随意复制、重新定义,甚至疯狂地修改它,直到你完全理解为止。
它使用了双向链表,这个在源文件的文档字符串中有说明。了解双向链表是怎么工作的,再加上浏览源代码,你就能很好地掌握它的具体工作原理:
# 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].