在Python 3.6+中按值对字典排序 [英] Sort Dict by Values in Python 3.6+

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

问题描述

经过几次尝试,我一直在寻找一种方法来对Python中的字典及其值进行排序:

I was looking for a method to sort a dictionary in Python with its values, after a few attempts, is what it comes:

a = {<populated dict...>}
a = {v: k for k, v in a.items()}
a = {v: k for k, v in sorted(a.items())}

此代码似乎可以正常工作,但我认为它的性能很差,有没有更好的方法?

This code seems to work, but I think it's poor for performance, is there a better way?

推荐答案

您不需要进行双键/值交换,您可以这样做:

You do not need to do the double key/value swap, you can do this:

a = {k: v for k, v in sorted(a.items(), key=lambda x: x[1])}

(已排序的 DOCS)

data = dict(a=1, b=3, c=2)
print(data)
data_sorted = {k: v for k, v in sorted(data.items(), key=lambda x: x[1])}
print(data_sorted)

结果:

从CPython 3.6开始:

Results:

From CPython 3.6:

{'a': 1, 'b': 3, 'c': 2}
{'a': 1, 'c': 2, 'b': 3}

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

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