首页 > 代码库 > sort a Python dictionary by value

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