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.
(sorted_x
将是一个元组列表,按每个元组中的第二个元素排序。)
dict(sorted_x) == x
. (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 [1] we can use
(在Python3中,由于不允许拆包[1],我们可以使用)
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
:
(如果要将输出作为字典,则可以使用collections.OrderedDict
:)
import collections
sorted_dict = collections.OrderedDict(sorted_x)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…