Python排序嵌套字典列表

2024-09-27 00:13:23 发布

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

我正在尝试用Python对嵌套字典进行排序。在

现在我有一本字典。在开始构建字典之前,我能够使用sortedon 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}};

但我想:

^{pr2}$

谢谢你的帮助!在


Tags: theapi字典排序mydictlistkey2key1
1条回答
网友
1楼 · 发布于 2024-09-27 00:13:23
>>> 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())

相关问题 更多 >

    热门问题