The usage of OrderedDict in python is explained in detail
- 2020-05-30 20:34:06
- OfStack
Many people think that the dictionary in python is unordered because it is stored as hash, but there is a module in python called collections(English, collection, collection) that comes with a subclass
OrderedDict, which sorts the elements in the dictionary object. See the following example:
import collections
print "Regular dictionary"
d={}
d['a']='A'
d['b']='B'
d['c']='C'
for k,v in d.items():
print k,v
print "\nOrder dictionary"
d1 = collections.OrderedDict()
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'
d1['1'] = '1'
d1['2'] = '2'
for k,v in d1.items():
print k,v
Output:
Regular dictionary
a A
c C
b B
Order dictionary
a A
b B
c C
1 1
2 2
As you can see, several elements such as ABC are also saved, but OrderedDict is sorted according to the order in which the elements are put. So the output values are sorted.
The dictionary objects of the OrderedDict object, if they are in a different order, then Python will also treat them as two different objects. See the example:
print 'Regular dictionary:'
d2={}
d2['a']='A'
d2['b']='B'
d2['c']='C'
d3={}
d3['c']='C'
d3['a']='A'
d3['b']='B'
print d2 == d3
print '\nOrderedDict:'
d4=collections.OrderedDict()
d4['a']='A'
d4['b']='B'
d4['c']='C'
d5=collections.OrderedDict()
d5['c']='C'
d5['a']='A'
d5['b']='B'
print d1==d2
Output:
Regular dictionary:
True
OrderedDict:
False
Here are some more examples:
dd = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
# According to the key The sorting
kd = collections.OrderedDict(sorted(dd.items(), key=lambda t: t[0]))
print kd
# In accordance with the value The sorting
vd = collections.OrderedDict(sorted(dd.items(),key=lambda t:t[1]))
print vd
# The output
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])