如何对嵌套字典python进行排序?

2024-05-21 04:49:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下嵌套字典:

{'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'}}

我想按开关排序,得到这个:

^{pr2}$

这可能吗?在


Tags: testip字典排序hostnamepr2switch2switch3
1条回答
网友
1楼 · 发布于 2024-05-21 04:49:43

请记住,python中的dict是无序列表,您可以使用OrderedDict来记住项目的顺序。在

下面的代码看起来确实对dict进行了排序(仅用于打印),但实际上并不是对其进行排序,您应该使用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())

相关问题 更多 >