我正在尝试在 Python 中对嵌套字典进行排序。
现在我有一本字典中的字典。在开始构建字典之前,我能够使用 sorted on the list 对外部键进行排序,但我无法同时对内部键进行排序。
我一直试图弄乱排序的 API,但仍然遇到问题。
现在我有:
myDict = {'A': {'Key3':4,'Key2':3,'Key4':2,'Key1':1},
'B': {'Key4':1,'Key3':2,'Key2':3,'Key1':4},
'C': {'Key1':4,'Key2':2,'Key4':1,'Key3':3}};
但我想:
myDict = {'A': {'Key1':1,'Key2':3,'Key3':4,'Key4':2},
'B': {'Key1':4,'Key2':3,'Key2':1,'Key4':1},
'C': {'Key1':4,'Key2':2,'Key3':3,'Key4':1}};
感谢您的帮助!
请您参考如下方法:
>>> from collections import OrderedDict
>>> def sortedDict(items):
... return OrderedDict(sorted(items))
>>> myDict = {'A': {'Key3':4,'Key2':3,'Key4':2,'Key1':1},
... 'B': {'Key4':1,'Key3':2,'Key2':3,'Key1':4},
... 'C': {'Key1':4,'Key2':2,'Key4':1,'Key3':3}}
>>> sortedDict((key, sortedDict(value.items())) for key, value in myDict.items())
