Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

python - 如何按值对字典排序?(How do I sort a dictionary by value?)

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.

(可能会更改我的代码以包含字典列表,但是由于我实际上并不需要字典列表,因此我想知道是否存在一种更简单的解决方案来按升序或降序进行排序。)

  ask by Gern Blanston translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...