How To Sort All The Keys, Sub-keys, Sub-sub-keys, Etc Of A Dictionary At Once?
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',
Solution 1:
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
Post a Comment for "How To Sort All The Keys, Sub-keys, Sub-sub-keys, Etc Of A Dictionary At Once?"