reference Adress:official Doc Learning Bolg
What?
An OrderedDict is a dictionary subclass that remembers the order in which its contents are added.
Compare with regular dict class, the OrderedDict remember the add sequentence and offer some functions to revise inner order;Intuitively,it more like a dict with list;
Feature?
1.Remember the order in which its contents are added
However Python3.7 dict has the same feature;So this feature is not matter any more;
1 | import collections |
1 | Regular dictionary: |
2.Offer functions to revise inner order
1.popitem(last=True)
The popitem() method for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in LIFO order if last is true or FIFO order if false.
2.move_to_end(key, last=True)
Move an existing key to either end of an ordered dictionary. The item is moved to the right end if last is true (the default) or to the beginning if last is false. Raises KeyError if the key does not exist:
1 | d = collections.OrderedDict.fromkeys('abcde') |
3.order-sensitive
A regular dict looks at its contents when testing for equality. An OrderedDict also considers the order the items were added.
1 | import collections |
Examples?
LRU function can be easility finished by OrderedDict.
1 | from collections import OrderedDict |