Ordered dictionary for introduction of python module (OrderedDict)

  • 2020-05-17 05:48:20
  • OfStack

Ordered dictionary - introduction to OrderedDict

The sample

An ordered dictionary is similar to a normal dictionary except that it records the order in which elements are inserted, whereas a 1-type dictionary iterates in any order. See the following example:


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 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 dictionaries are not normally traversed in insertion order.

equality

Determining whether two ordered fields are equal (==) takes into account whether the order in which the elements are inserted 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 results are as follows:


-> python test7.py
dict    : True
OrderedDict: False

And when you decide if an ordered dictionary is equal to other regular dictionaries you just have to decide if the content is equal.

Pay attention to

The constructor of OrderedDict or the update() method accepts keyword arguments, but because python's function calls pass the arguments using an unordered dictionary, the order of the keyword arguments is lost, so the created ordered dictionary does not guarantee the order.

The resources

https://docs.python.org/2/library/collections.html#collections.OrderedDict
https://pymotw.com/2/collections/ordereddict.html


Related articles: