python - 如何按值对字典进行排序?

我有一个从数据库中的两个字段读取的值字典:一个字符串字段和一个数字字段。字符串字段是唯一的,所以是字典的键。

我可以按键排序,但如何根据值排序?

注意:我在这里阅读了堆栈溢出问题 How do I sort a list of dictionaries by a value of the dictionary? 并且可能可以将我的代码更改为有一个字典列表,但由于我真的不需要字典列表,我想知道是否有更简单的解决方案来按升序或降序排序。

最佳答案

Python 3.7+ 或 CPython 3.6

字典在 Python 3.7+ 中保留插入顺序。在 CPython 3.6 中相同,但 it's an implementation detail .

>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

旧版 Python

无法对字典进行排序,只能获取已排序字典的表示形式。字典本质上是无序的,但其他类型,例如列表和元组,则不是。所以你需要一个有序的数据类型来表示排序后的值,这将是一个列表——可能是一个元组列表。

例如,

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

sorted_x 将是按每个元组中的第二个元素排序的元组列表。 dict(sorted_x) == x.

对于那些希望按键而不是值进行排序的人:

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

在 Python3 中自 unpacking is not allowed我们可以使用

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])

如果您希望输出为 dict,您可以使用 collections.OrderedDict :

import collections

sorted_dict = collections.OrderedDict(sorted_x)

https://stackoverflow.com/questions/613183/

相关文章:

python - 在 'for' 循环中访问索引

python - 如何从列表列表中制作平面列表?

python - @staticmethod 和 @classmethod 之间的区别

python - 查找列表中项目的索引

python - 了解切片

python - Python 的列表方法 append 和 extend 有什么区别?

python - 使用 'for' 循环遍历字典

python - 如何检查列表是否为空?

python - 检查给定键是否已存在于字典中

python - 在函数中使用全局变量