shaveax shaveax - 1 year ago 78
Python Question

how to sort nested dictionary python?

i have the following nested dictionary:

{'switch3': {'ip': '192.160.1.2', 'hostname': 'test-1'},
'switch2': {'ip': '192.160.1.8', 'hostname': 'test-1'},
'switch4': {'ip': '192.160.1.3', 'hostname': 'test-1'},
'switch1': {'ip': '192.160.1.4', 'hostname': 'test-1'}}


and i want to sort by switch, and get this :

{'switch1': {'ip': '192.160.1.4', 'hostname': 'test-1'}
'switch2': {'ip': '192.160.1.8', 'hostname': 'test-1'},
'switch3': {'ip': '192.160.1.2', 'hostname': 'test-1'},
'switch4': {'ip': '192.160.1.3', 'hostname': 'test-1'}}


is this possible ?

Answer Source

Keep in mind that dicts in python are unordered list, You can use the OrderedDict that remember the order of the items.

The following code does seem to sort the dict (only for print), but it's not actually sort it, you should use OrderedDict.

mydict = {'switch3': {'ip': '192.160.1.2', 'hostname': 'test-1'}, 
'switch2': {'ip': '192.160.1.8', 'hostname': 'test-1'}, 
'switch4': {'ip': '192.160.1.3', 'hostname': 'test-1'}, 
'switch1': {'ip': '192.160.1.4', 'hostname': 'test-1'}}

sorted_x = sorted(mydict.items())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download