如何按值对字典排序? [英] How do I sort a dictionary by value?

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

问题描述

我有一个从数据库的两个字段中读取的值的字典:字符串字段和数字字段.字符串字段是唯一的,因此这是字典的键.

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.

我可以对键进行排序,但是如何根据值进行排序?

I can sort on the keys, but how can I sort based on the values?

注意:我已经在这里阅读了堆栈溢出问题 如何按字典值对字典列表进行排序? ,并且可能会更改我的代码以包含字典列表,但是由于我实际上并不需要字典列表,因此我想知道是否存在更简单的解决方案来按升序或降序进行排序. /p>

Note: I have read Stack Overflow question here How do I sort a list of dictionaries by a value of the dictionary? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution to sort either in ascending or descending order.

推荐答案

Python 3.6 +

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

旧版Python

不可能对字典进行排序,而只能获得所排序字典的表示形式.字典本质上是无序的,但其他类型(例如列表和元组)不是.因此,您需要一种有序的数据类型来表示排序后的值,这将是一个列表-可能是一个元组列表.

Older Python

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

例如,

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

sorted_x将是按每个元组中的第二个元素排序的元组列表. dict(sorted_x) == x.

sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.

对于那些希望对键而不是值进行排序的人:

And for those wishing to sort on keys instead of values:

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

在Python3中,由于不允许拆包,因此 [1] 我们可以使用

In Python3 since unpacking is not allowed [1] we can use

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])

如果要将输出作为字典,则可以使用 :

If you want the output as a dict, you can use collections.OrderedDict:

import collections

sorted_dict = collections.OrderedDict(sorted_x)

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

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