且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-18 21:43:18

Python 3.7+ 或 CPython 3.6

字典在 Python 3.7+ 中保留插入顺序.在 CPython 3.6 中相同,但这是一个实现细节.

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

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

例如

导入操作符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.

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

导入操作符x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}sorted_x = sorted(x.items(), key=operator.itemgetter(0))

在Python3中,由于不允许解包我们可以使用

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

如果你想要输出作为字典,你可以使用 collections.OrderedDict:

导入集合sorted_dict = collections.OrderedDict(sorted_x)

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.

I can sort on the keys, but how can I sort based on the values?

Note: I have read Stack Overflow question here How do I sort a list of dictionaries by a value of the dictionary? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution to sort either in ascending or descending order.

Python 3.7+ or CPython 3.6

Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but 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}

or

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

Older Python

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

For instance,

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

sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.

And for those wishing to sort on keys instead of values:

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

In Python3 since unpacking is not allowed we can use

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

If you want the output as a dict, you can use collections.OrderedDict:

import collections

sorted_dict = collections.OrderedDict(sorted_x)