python - 基于Key对Python字典进行排序?

标签 python sorting python-2.7 dictionary

<分区>

我创建了一个 python 字典,其中包含以下形式的键:

11, 10, 00, 01, 20, 21, 31, 30

键是字符串

我想按照这些排序顺序维护我的字典:

00, 10, 20, 30, 01, 11, 21, 31 

这是基于键的第二个值。

我尝试了这个 sorted(dict.items(), key = lambda s: s[1]) 并得到了这样的键:

20, 30, 21, 31, 01, 11, 10, 00

有人可以指导我吗?

最佳答案

你几乎已经成功了,但关键是元组的第一项:

sorted(dict.items(), key=lambda s: s[0])

关于python - 基于Key对Python字典进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18949161/

相关文章:

python - TensorFlow concat 中的排名不匹配错误

python - 类型错误 : Value passed to parameter 'a' has DataType not in list of allowed values

python - 如何将 Plotly dash 应用程序放在 protected 路线后面

python - QMessageBox 改变标准按钮的文本

python - 在 Linux 中获取 Windows 路径的基本名称

python - nltk Sentiwordnet 与 python 的结合使用

python - 如何根据日期索引连接一系列数据以形成 df 而不会丢失数据

java - 按字母顺序对列表进行排序,头部有特定值(如果存在)

c - C题中的冒泡排序

C++ STL - STL sort() 的第三个参数如何工作?