如何按值排序Python字典?

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))
LEARN MORE  HTTP Status 503 Error Code and How To Fix It?
了解更多HTTP状态503错误代码以及如何解决?

翻译自: https://www.poftut.com/how-to-sort-python-dictionary-by-value/

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值