I have a dictionary that looks like this:
myDict = {
\'SER12346\': {\'serial_num\': \'SER12346\', \'site_location\': \'North America\'},
\'ABC12345\'
Dictionaries do not preserve order of items - hence can not be sorted. If you want an appearance of sorted dictionary, you need to make a sorted list and then insert it into OrderedDict class. Code snippet below illustrates this:
from collections import OrderedDict
myDict = {
'SER12346': {'serial_num': 'SER12346', 'site_location': 'North America'},
'ABC12345': {'serial_num': 'ABC12345', 'site_location': 'South America'},
'SER12345': {'serial_num': 'SER12345', 'site_location': 'North America'},
'SER12347': {'serial_num': 'SER12347', 'site_location': 'South America'},
'ABC12346': {'serial_num': 'ABC12346', 'site_location': 'Europe'}
}
def sortfun(d):
return (d[1]['site_location'], d[1]['serial_num'])
skv = sorted(myDict.iteritems(), key=sortfun)
sorted_dict = OrderedDict(skv)
print sorted_dict