根据密钥对Python字典进行排序? [英] Sorting Python Dictionary based on Key?
本文介绍了根据密钥对Python字典进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个python字典,其中包含以下形式的键:
I have created a python dictionary which has keys in this form :
11, 10, 00, 01, 20, 21, 31, 30
键是字符串
我想按以下顺序维护字典:
I would like to maintain my dictionary in these sorted order:
00, 10, 20, 30, 01, 11, 21, 31
这是基于键的第二个值.
This is based on the second value of the key.
我尝试了这个sorted(dict.items(), key = lambda s: s[1])
,并得到了像这样的键:
I tried this sorted(dict.items(), key = lambda s: s[1])
and got the keys like:
20, 30, 21, 31, 01, 11, 10, 00
有人可以引导我吗?
推荐答案
您几乎拥有它,但关键是元组的第一项:
You almost had it, but the key is the first item of the tuple:
sorted(dict.items(), key=lambda s: s[0])
这篇关于根据密钥对Python字典进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文