简体   繁体   中英

python: use sorted() function for dict inside the dict

this is the dict I got now:

dict1 = {1: {7: [6], 1: [7]}, 2: {3: [1, 6], 2: [2, 7, 5]}}

And I would like to order subdictionary by keys:

dict2 = {1: {1: [7], 7: [6]}, 2: {2: [2, 7, 5], 3: [1, 6]}}

I tried some methods, but it didn't work...Like this one. Please help me.

print(sorted(dict1.items(), key=lambda x: x[1][1]))

As long as you use sufficiently high version of Python3 you can do:

dict1 = {1: {7: [6], 1: [7]}, 2: {3: [1, 6], 2: [2, 7, 5]}}

dict2 = {k: dict(sorted(v.items())) for k, v in dict1.items()}
print(dict2)

Prints:

{1: {1: [7], 7: [6]}, 2: {2: [2, 7, 5], 3: [1, 6]}}

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