简体   繁体   English

python:对字典内的字典使用 sorted() function

[英]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]}} 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]}} 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:只要您使用足够高版本的 Python3,您就可以:

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]}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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