An introduction to ordered dictionary-ordereddict
Example
An ordered dictionary is similar to a common dictionary, except that it can record the order in which an element is inserted, whereas a generic dictionary is iterated in any order. See the example below:
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 results of the operation are as follows:
Python test7.pyregular dictionary:a Ac Cb be Ed dordereddict:a Ab Bc Cd De E
You can see that dictionaries are usually not traversed in an insertion order.
Equality of
Determines whether two ordered fields are equal (= =) to consider whether the order of the elements 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 results of the operation are as follows:
Python test7.pydict : Trueordereddict:false
And when judging whether an ordered dictionary and other ordinary dictionaries are equal, simply determine whether the content is equal.
Attention
The Ordereddict constructor or update () method accepts the keyword argument, but because Python's function calls use an unordered dictionary to pass arguments, the order of the keyword arguments is lost, so the ordered dictionary created does not guarantee its order.
Resources
Https://docs.python.org/2/library/collections.html#collections.OrderedDict
Https://pymotw.com/2/collections/ordereddict.html