how can i sort the nested dictionary alphabetically?

This worked for me, for each key, I sort its subdictionary.

dict_1={'Ivanov': {'aaa': 52, 'bbb': 3, 'ccc': 45, 'paper': 17, 'marker': 3, 'envelope': 5},   'Petrov': {'aaa': 9, 'bbb': 7, 'ddd': 34, 'pens': 5, 'envelope': 20},'Sidorov': {'aaa': 356},'Ziborov': {'eee': 234}} 

def sort(dict_input):
    #Sorting subdictionaries
    dict_output={}
    for i in sorted(dict_input):
        dict_output[i]=dict_input[i]
    return dict_output
        
dict_2={}
for key in sorted(dict_1):
    #For each key, sorting subdictionary
    dict_2[key]=sort(dict_1[key])
print(dict_2)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top