简体   繁体   中英

How to sort nested dictionaries?

>>> My_dic = {752: (5,34),96:[1,2,{'wow':[6,9,178,-24,56], "Why":4,"much":[83,0,-56,7,98]}], 495:"too"}

>>> My_dic= res = My_dic(sorted(My_dic.items(), 
       key = lambda x: My_dic(x[1],[1])))
>>> My_dic= res = My_dic(sorted(My_dic.items(),key = lambda x: My_dic(x[1],["much"])


    My_dic = {752: (5,34),96:{'wow':[6,9,178,-24,56], "Why":4,"much":[83,0,-56,7,98]}, 495:"too"}

I am sorting partial order of a python nested dictionary. I am trying to sort [83,0,-56,7,98] next to "much" using sort. If you can help me sort the nested dictionary part, I would appreciate it.

Try this mate

my_dict = {
    752: (5,34),
    96: {
        'wow': [6, 9, 178, -24, 56], 
        "Why": 4,
        "much": [83, 0, -56, 7, 98]
    }, 
    495: "too",
}

dict_keys = my_dict.keys()

for key in dict_keys:
    if type(my_dict.get(key)) is dict and my_dict.get(key).get('much'):
        my_dict[key]['much'] = sorted(my_dict[key]['much'])

print(my_dict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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