您当前的位置: 首页 >  彭世瑜 Python

Python编程:字典排序sorted问题

彭世瑜 发布时间:2019-02-19 13:44:33 ,浏览量:2

思路:字典转为包含元组的列表排序

代码示例

dct = {
	"百度": 30,
	"阿里": 20,
	"腾讯": 25
}
print(dct)
# {'百度': 30, '阿里': 20, '腾讯': 25}


# 从小到大排序
dct_sorted = sorted(dct.items(), key=lambda item: item[1])
print(dct_sorted)
# [('阿里', 20), ('腾讯', 25), ('百度', 30)]


# 从大到小排序
dct_sorted_reverse = sorted(dct.items(), key=lambda item: item[1], reverse=True)
print(dct_sorted_reverse)
# [('百度', 30), ('腾讯', 25), ('阿里', 20)]

上面的代码使用lambda 表达式,还可以使用operator模块提供的方式

# -*- coding: utf-8 -*-

import operator

dct = {
    "百度": 30,
    "阿里": 20,
    "腾讯": 25
}

sorted_dict = sorted(dct.items(), key=operator.itemgetter(1))
print(sorted_dict)
# [('阿里', 20), ('腾讯', 25), ('百度', 30)]

关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 2浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0794s