The dictionary is unordered, but the OrderedDict class of collections provides us with an Ordered dictionary structure, which is a real Ordered + Dict, the following two examples are used to briefly understand the OrderedDict ordered dictionary in the collections module of Python: as the data structure name says, it records the order in which each key-value pair is added.
d = OrderedDict()d['a'] = 1d['b'] = 10d['c'] = 8for letter in d: print letter
Output:
abc
If multiple parameters are input at the same time during initialization, their order is random and will not be stored in order of location.
>>> d = OrderedDict(a=1, b=2, c=3)OrderedDict([('a', 1), ('c', 3), ('b', 2)])
In addition to the same method as normal dict, OrderedDict also provides sequence-related operations: + popitem (): returns the last inserted key-value pair, if popitem (last = False) is returned, the first inserted key-value pair + reversed is returned.
Instance
In fact, OrderedDict can be viewed as a dictionary subclass:
import collectionsprint 'Regular dictionary:'d = {}d['a'] = 'A'd['b'] = 'B'd['c'] = 'C'for k, v in d.items(): print k, vprint '\nOrderDict:'d = collections.OrderedDict()d['a'] = 'A'd['b'] = 'B'd['c'] = 'C'for k, v in d.items(): print k, v
Conventional dict does not track the insertion sequence. iterative processing generates values based on the order in which keys are stored in the hash table. In OrderDict, it remembers the order of element insertion and uses this order when creating the iterator.
Regular dictionary:a Ac Cb BOrderDict:a Ab Bc C
Regular dict checks its content for equality, while OrderDict also considers the order in which elements are added.