sort a Python dictionary by value
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sort a Python dictionary by value相关的知识,希望对你有一定的参考价值。
首先要明确一点,Python的dict本身是不能被sort的,更明确地表达应该是“将一个dict通过操作转化为value有序的列表”
有以下几种方法:
1.
import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1)) #sorted by value sorted_x = sorted(x.items(), key=operator.itemgetter(0)) #sorted by key
2.
sorted(dict1, key=dict1.get)
3.
sorted(d.items(), key=lambda x: x[1])
4.
sorted([(value,key) for (key,value) in mydict.items()])
5. Use OrderedDict
>>> # regular unsorted dictionary >>> d = {‘banana‘: 3, ‘apple‘: 4, ‘pear‘: 1, ‘orange‘: 2} >>> # dictionary sorted by key >>> OrderedDict(sorted(d.items(), key=lambda t: t[0])) OrderedDict([(‘apple‘, 4), (‘banana‘, 3), (‘orange‘, 2), (‘pear‘, 1)]) >>> # dictionary sorted by value >>> OrderedDict(sorted(d.items(), key=lambda t: t[1])) OrderedDict([(‘pear‘, 1), (‘orange‘, 2), (‘banana‘, 3), (‘apple‘, 4)]) >>> # dictionary sorted by length of the key string >>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0]))) OrderedDict([(‘pear‘, 1), (‘apple‘, 4), (‘orange‘, 2), (‘banana‘, 3)])
以上是关于sort a Python dictionary by value的主要内容,如果未能解决你的问题,请参考以下文章