We have a dictionary which is read from a file. One field is string other field is number. String fields are unique and used as keys. Sorting by keys is easy but how can we sort them by values
我们有一个从文件中读取的字典。 一个字段是字符串,另一个字段是数字。 字符串字段是唯一的,并且用作键。 按键排序很容易,但如何按值排序
范例字典(Example Dictionary)
We have the following dictionary which is consist of string and numbers.
我们有以下由字符串和数字组成的字典。
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
By the way, we are using python interpreter to make things more interactive and easy
顺便说一句,我们正在使用python解释器使事情更交互和更容易
按值对它们进行排序(Sort Them By Value)
We will sort them by value and create a list of tuples
我们将按值对它们进行排序并创建一个元组列表
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
完整词典排序示例 (Complete Dictionary Sort Example)
We will have following a full script which can sort the given dictionary by value.
我们将遵循一个完整的脚本,该脚本可以按值对给定的字典进行排序。
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
翻译自: https://www.poftut.com/how-to-sort-python-dictionary-by-value/