OrderedDict and pythonordereddict
Ordered dictionary-OrderedDict Introduction
Example
An ordered dictionary is similar to a common dictionary, but it records the order in which elements are inserted, while a general dictionary iterates in any order. See the following example:
import collectionsprint 'Regular dictionary:'d = {}d['a'] = 'A'd['b'] = 'B'd['c'] = 'C'd['d'] = 'D'd['e'] = 'E'for k, v in d.items(): print k, vprint '\nOrderedDict:'d = collections.OrderedDict()d['a'] = 'A'd['b'] = 'B'd['c'] = 'C'd['d'] = 'D'd['e'] = 'E'for k, v in d.items(): print k, v
The running result is as follows:
-> python test7.pyRegular dictionary:a Ac Cb Be Ed DOrderedDict:a Ab Bc Cd De E
We can see that the dictionary is not traversed in the insert order.
Equality
To determine whether two ordered fields are equal (=), consider whether the order of element insertion is equal.
import collectionsprint 'dict :',d1 = {}d1['a'] = 'A'd1['b'] = 'B'd1['c'] = 'C'd1['d'] = 'D'd1['e'] = 'E'd2 = {}d2['e'] = 'E'd2['d'] = 'D'd2['c'] = 'C'd2['b'] = 'B'd2['a'] = 'A'print d1 == d2print 'OrderedDict:',d1 = collections.OrderedDict()d1['a'] = 'A'd1['b'] = 'B'd1['c'] = 'C'd1['d'] = 'D'd1['e'] = 'E'd2 = collections.OrderedDict()d2['e'] = 'E'd2['d'] = 'D'd2['c'] = 'C'd2['b'] = 'B'd2['a'] = 'A'print d1 == d2
The running result is as follows:
-> python test7.pydict : TrueOrderedDict: False
When determining whether an ordered dictionary is equal to other common dictionaries, you only need to determine whether the content is equal.
Note:
Although the OrderedDict constructor or the update () method accepts the keyword parameter, the order of the keyword parameter is lost because the python function call uses an unordered dictionary to pass the parameter, therefore, the order of the created ordered dictionary cannot be guaranteed.
References
Https://docs.python.org/2/library/collections.html#collections.OrderedDict
Https://pymotw.com/2/collections/ordereddict.html