繁体   English   中英

如何对多维字典中的键进行排序

[英]How to sort keys in multidimensional dict

我有多维字典:

my_dict = {
    "first": {
        "bbb": "aaa",
        "ccc": "sdfs",
        "aaa": "123"
    },
    "other": {
        "ttt": "a",
        "e": "e",
        "yy": "y"
    },
    "aaa": {
        "q": "a",
        "e": "e",
        "r": "y"
    }
}

我想根据字母顺序对字典中的第二个维度进行排序。 我想收到:

my_new_dict = {
    "first": {
        "aaa": "123",
        "bbb": "aaa",
        "ccc": "sdfs"
    },
    "other": {
        "e": "e",
        "ttt": "a",
        "yy": "y"
    },
    "aaa": {
        "e": "e",
        "q": "a",
        "r": "y"
    }
}

我努力了:

my_new_dict = sorted(my_dict.items(), key=lambda x: lambda y: y[0])

但这返回了我的错误:

TypeError:“dict”和“dict”的实例之间不支持“<”。

您可以对每个子词典使用sorted

my_dict = { "first": { "bbb": "aaa", "ccc": "sdfs", "aaa": "123" }, "other": { "ttt": "a", "e": "e", "yy": "y" }, "aaa": { "q": "a", "e": "e", "r": "y" } }

output = {k: dict(sorted(v.items())) for k, v in my_dict.items()}

print(output)
# {'first': {'aaa': '123', 'bbb': 'aaa', 'ccc': 'sdfs'},
#  'other': {'e': 'e', 'ttt': 'a', 'yy': 'y'},
#  'aaa': {'e': 'e', 'q': 'a', 'r': 'y'}}

请注意,字典的“排序”保证仅适用于 python 3.7+。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM