按值对字典进行排序python [英] sort dict by value python

查看:46
本文介绍了按值对字典进行排序python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字典.

data = {1:'b', 2:'a'}

我想按b"和a"对数据进行排序,以便得到结果

And I want to sort data by 'b' and 'a' so I get the result

'a','b'

我该怎么做?
有什么想法吗?

How do I do that?
Any ideas?

推荐答案

获取值使用

sorted(data.values())

要获取匹配的键,请使用 key 函数

To get the matching keys, use a key function

sorted(data, key=data.get)

获取按值排序的元组列表

To get a list of tuples ordered by value

sorted(data.items(), key=lambda x:x[1])

相关:请参阅此处的讨论:字典在 Python 3.6+ 中排序

Related: see the discussion here: Dictionaries are ordered in Python 3.6+

这篇关于按值对字典进行排序python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆