按值排序Python字典 [英] Sort a Python dictionary by value

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

问题描述

我有一个值从数据库中的两个字段读取的值:字符串字段和数字字段。字符串字段是唯一的,所以这是字典的关键。

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?

注意:我已经阅读了Stack Overflow问题如何按照Python中的字典,并且可能会将我的代码更改为具有字典列表,但是由于我真的不需要一个字典列表,我想知道如果有一个更简单的解决方案。

Note: I have read Stack Overflow question How do I sort a list of dictionaries by values of the dictionary in Python? 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.

推荐答案

不可能对dict进行排序,只能获取排序的dict的表示形式。判决本质上是无序的,但其他类型,如列表和元组,则不是。所以你需要一个排序的表示,这将是一个列表,可能是一个元组列表。

It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So you need a sorted representation, 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

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

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))

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

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