Home >Backend Development >Python Tutorial >Python ordered dictionary
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 the 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 result is 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
And when judging whether an ordered dictionary is equal to other ordinary dictionaries, only It is necessary to determine whether the contents are equal.
Note
OrderedDict's constructor or update() method accepts keyword parameters, but because python function calls use unordered dictionaries to pass parameters, the order of keyword parameters will be lost, so what is created is An ordered dictionary does not guarantee its order.