Many people think that dictionaries in python are unordered because they are stored according to hash, but there is a module collections (in English, collection, set) in python which comes with a subclass
OrderedDict, which implements sorting of elements in a dictionary object. See the example below:
import collections print "Regular dictionary" d={} d['a']='A' d['b']='B' d['c']='C' for k,v in (): print k,v print "\nOrder dictionary" d1 = () d1['a'] = 'A' d1['b'] = 'B' d1['c'] = 'C' d1['1'] = '1' d1['2'] = '2' for k,v in (): 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, the same ABC and other elements are saved, but the use of OrderedDict will be sorted according to the order in which the elements are placed. So the output value is sorted.
OrderedDict object of the dictionary object, if its order is different then Python will also treat them as two different objects, see 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=() d4['a']='A' d4['b']='B' d4['c']='C' d5=() d5['c']='C' d5['a']='A' d5['b']='B' print d1==d2
Output:
Regular dictionary:
True
OrderedDict:
False
Look at a few more examples:
dd = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} # Sort by key kd = (sorted((), key=lambda t: t[0])) print kd # Sort by value vd = (sorted((),key=lambda t:t[1])) print vd # Output OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
This is the whole content of this article.