Home >Backend Development >Python Tutorial >Introduction to python module: Ordered Dict (OrderedDict)
Ordered Dictionary-Introduction to OrderedDict
Example
An ordered dictionary is similar to a normal dictionary, except that it can record the order in which elements are inserted into it, while a normal dictionary will iterate in any order. See example below:
import collections print '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, v print '\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 results are as follows:
-> python test7.py Regular dictionary: a A c C b B e E d D OrderedDict: a A b B c C d D e E
You can see that usually dictionaries are not traversed in insertion order.
Equality
To determine whether two ordered fields are equal (==), you need to consider whether the order of element insertion is equal
import collections print '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 == d2 print '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 results are as follows:
-> python test7.py dict : True OrderedDict: False
When judging whether an ordered dictionary is equal to other ordinary dictionaries, you only need to judge whether the contents are equal.
Attention
Although the constructor or update() method of OrderedDict accepts keyword parameters, because python function calls use unordered dictionaries to pass parameters, the order of keyword parameters will be lost, so the created ordered dictionary cannot be guaranteed. its order.
References
https://docs.python.org/2/library/collections.html#collections.OrderedDict
https://pymotw.com/2/collections/ordereddict.html