My question is an extension to another question where the OP has a dictionary, the one below, and wants to sort main keys based on the sub-dictionary keys
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'}
}
The proposed (quoted below) solution works perfectly.
dicts = myDict.items()
dicts.sort(key=lambda (k,d): (d['site_location'], d['serial_num'],))
However this solution does sorting in ascending order for all (sorting in descending order is straightforward). I was wondering if it is possible to define mix of sorting order, say serial_num
in ascending but site_location
in descending order?
Method #1 : Using OrderedDict() + sorted() This task can be performed using OrderedDict function which converts the dictionary to specific order as mentioned in its arguments manipulated by sorted function in it to sort by the value of key passed.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
To sort dictionary key in python we can use dict. items() and sorted(iterable) method. Dict. items() method returns an object that stores key-value pairs of dictionaries.
This is one solution, possible because list sorting is stable. I changed the data slightly to demonstrate that it works.
This method is also prescribed in the Python documentation.
myDict = {
'SER12346': {'serial_num': 'SER12346', 'site_location': 'North America'},
'ABC12346': {'serial_num': 'ABC12345', 'site_location': 'Europe'},
'ABC12345': {'serial_num': 'ABC12345', 'site_location': 'South America'},
'SER12345': {'serial_num': 'SER12345', 'site_location': 'North America'},
'SER12347': {'serial_num': 'SER12347', 'site_location': 'South America'}
}
result = sorted(myDict.items(), key=lambda x: x[1]['site_location'], reverse=True)
result = sorted(result, key=lambda x: x[1]['serial_num'])
# [('ABC12345', {'serial_num': 'ABC12345', 'site_location': 'South America'}),
# ('ABC12346', {'serial_num': 'ABC12345', 'site_location': 'Europe'}),
# ('SER12345', {'serial_num': 'SER12345', 'site_location': 'North America'}),
# ('SER12346', {'serial_num': 'SER12346', 'site_location': 'North America'}),
# ('SER12347', {'serial_num': 'SER12347', 'site_location': 'South America'})]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With