如何一次对字典的所有键、子键、子子键等进行排序?

How to sort all the keys, sub-keys, sub-sub-keys, etc of a dictionary at once?

有没有办法一次对python字典的所有键、子键、子子键等进行排序?

假设我有字典

dict_1 = { 
            "key9":"value9",
            "key5":"value5",
            "key3":{
                    "key3_1":"value3_1",
                    "key3_3":"value3_3",
                    }
            "key4":"value4",
            "key2":"value2",
            "key8":{
                    "key8_1":"value8_1",
                    "key8_5":[                              
                              "value8_5_3",
                              "value8_5_1",
                              ]
                    "key8_2":"value8_2",
                    }
            "key4":"value4",            
            "key1":"value1",
         }

我希望它排序为

dict_1 = { 
        "key1":"value1",
        "key2":"value2",
        "key3":{
                "key3_1":"value3_1",
                "key3_3":"value3_3",                    
                }
        "key4":"value4",
        "key5":"value5",                        
        "key8":{
                "key8_1":"value8_1",
                "key8_2":"value8_2",
                "key8_5":[
                          "value8_5_1",                 
                          "value8_5_3",                 
                          ]                 
                }           
        "key9":"value9",
     }      

有方法吗?

请注意:

首先,重要的是要知道字典是无序的。所以,如果你想订购字典,你需要使用 collections.OrderedDict (自 Python 2.7 以来就存在)。

然后,这是一个递归函数的用例:

from collections import OrderedDict


def order_dict(d):
    ordered_dict = OrderedDict()
    for key in sorted(d.keys()):
        val = d[key]
        if isinstance(val, dict):
            val = order_dict(val)
        ordered_dict[key] = val
    return ordered_dict