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

Python 如何对嵌套字典进行排序?,python,sorting,dictionary,Python,Sorting,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'}} 我想按开关排序,得到这

我有以下嵌套字典:

{'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'}}
我想按开关排序,得到这个:

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

这可能吗?

请记住,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())

字典是无序的,因此不能对字典进行排序。您可以将它们转换为(已排序的)列表…字典没有排序(在CPython 3.6之前),应用
sorted()
,然后传递到
orderedict
orderedict
在Python 3.6中仍然是正确的集合;不要依赖于实现。你能举个例子吗?Nice的可能复制品
key=lambda p:p[0]
较短,但与描述性差不多。@Ryan
operator.itemgetter
更快。无论如何,这里都不需要,
sorted()!见duplicate@Ryan嗯。。它比较短;)@Chris_Rands,我已经阅读了重复链接,似乎你是对的,修复了它。谢谢你的注意。@omri_saadon如果这是一个副本,就把它标记为一个,然后继续