Is there a way to sort all the keys, sub-keys, sub-sub-keys, etc. of a python dictionary at once?
Let's suppose I have the dictionary
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",
}
and I want it sorted as
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",
}
Is there a method to do it?
Please note:
potentially my
dict_1
could have several levels of subkeys (nested dictionaries) or subvalues (nested lists).I am using Python 2.7.17, and I cannot update it. But order is not preserved in dictionaries of Python versions previous to 3.7, so I bet the sorting has to be done by using the OrderedDict.
CodePudding user response:
First, it is important to know that dictionaries are not ordered. So, if you want to order a dict, you need to go with collections.OrderedDict
(which exists since Python 2.7
).
And then, this is a use case for a recursive function:
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