-3

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 ?

Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
shaveax
  • 458
  • 6
  • 16

1 Answers1

1

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())
omri_saadon
  • 10,193
  • 7
  • 33
  • 58