gpt4 book ai didi

Python排序嵌套字典列表

转载 作者:太空宇宙 更新时间:2023-11-04 05:24:02 24 4
gpt4 key购买 nike

我正在尝试在 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())

关于Python排序嵌套字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39403450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com