# Python如何按值对字典进行排序？

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

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

```

## 简单如下： `sorted(dict1, key=dict1.get)`

``````from collections import defaultdict
d = defaultdict(int)
for w in text.split():
d[w] += 1``````

``````for w in sorted(d, key=d.get, reverse=True):
print w, d[w]``````

`sorted(d.items(), key=lambda x: x[1])`

``sorted(d.values())``

（键，值）对的列表，按值排序：

``````from operator import itemgetter
sorted(d.items(), key=itemgetter(1))``````

``````>>> d = {"third": 3, "first": 1, "fourth": 4, "second": 2}

>>> for k, v in d.items():
...     print "%s: %s" % (k, v)
...
second: 2
fourth: 4
third: 3
first: 1

>>> d
{'second': 2, 'fourth': 4, 'third': 3, 'first': 1}``````

``````>>> from collections import OrderedDict
>>> d_sorted_by_value = OrderedDict(sorted(d.items(), key=lambda x: x[1]))``````

OrderedDict的行为像一个正常的字典：

``````>>> for k, v in d_sorted_by_value.items():
...     print "%s: %s" % (k, v)
...
first: 1
second: 2
third: 3
fourth: 4

>>> d_sorted_by_value
OrderedDict([('first': 1), ('second': 2), ('third': 3), ('fourth': 4)])``````

``````from operator import itemgetter
from collections import OrderedDict

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = OrderedDict(sorted(x.items(), key=itemgetter(1)))
# OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)])``````

``````# regular unsorted dictionary
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

# dictionary sorted by value
OrderedDict(sorted(d.items(), key=lambda t: t[1]))
# OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])``````

``````import collections
Player = collections.namedtuple('Player', 'score name')
d = {'John':5, 'Alex':10, 'Richard': 7}``````

``worst = sorted(Player(v,k) for (k,v) in d.items())``

``best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)``

``````player = best[1]
player.name
'Richard'
player.score
7``````

# 从Python 3.6开始，内置的字典将会被订购

``SELECT a_key, a_value FROM a_table ORDER BY a_value;``

``````k_seq = ('foo', 'bar', 'baz')
v_seq = (0, 1, 42)
ordered_map = dict(zip(k_seq, v_seq))``````

``````for k, v in ordered_map.items():
print(k, v)``````

``````foo 0
bar 1
baz 42``````

``````bar 1
foo 0
baz 42``````

## 细节：

• 关键字参数和
• （中级）dict存储

Raymond Hettinger亲切地提供了解释“ The Python Behind Python 3.6 Dictionaries ”的文档- 来自他的旧金山Python Meetup Group发布的2016-DEC-08。

### 2017-12-15更新：

``WantedOutput = sorted(MyDict, key=lambda x : MyDict[x]) ``

（回答“不可能排序字典”的人没有读到这个问题！事实上，“我可以对键进行排序，但是我怎样才能根据这些值进行排序？”显然意味着他想要一个列表按照它们的值的值排序的键）。

``````import operator
origin_list = [
{"name": "foo", "rank": 0, "rofl": 20000},
{"name": "Silly", "rank": 15, "rofl": 1000},
{"name": "Baa", "rank": 300, "rofl": 20},
{"name": "Zoo", "rank": 10, "rofl": 200},
{"name": "Penguin", "rank": -1, "rofl": 10000}
]
print ">> Original >>"
for foo in origin_list:
print foo

print "\n>> Rofl sort >>"
for foo in sorted(origin_list, key=operator.itemgetter("rofl")):
print foo

print "\n>> Rank sort >>"
for foo in sorted(origin_list, key=operator.itemgetter("rank")):
print foo``````

``````{'name': 'foo', 'rank': 0, 'rofl': 20000}
{'name': 'Silly', 'rank': 15, 'rofl': 1000}
{'name': 'Baa', 'rank': 300, 'rofl': 20}
{'name': 'Zoo', 'rank': 10, 'rofl': 200}
{'name': 'Penguin', 'rank': -1, 'rofl': 10000}``````

ROFL

``````{'name': 'Baa', 'rank': 300, 'rofl': 20}
{'name': 'Zoo', 'rank': 10, 'rofl': 200}
{'name': 'Silly', 'rank': 15, 'rofl': 1000}
{'name': 'Penguin', 'rank': -1, 'rofl': 10000}
{'name': 'foo', 'rank': 0, 'rofl': 20000}``````

``````{'name': 'Penguin', 'rank': -1, 'rofl': 10000}
{'name': 'foo', 'rank': 0, 'rofl': 20000}
{'name': 'Zoo', 'rank': 10, 'rofl': 200}
{'name': 'Silly', 'rank': 15, 'rofl': 1000}
{'name': 'Baa', 'rank': 300, 'rofl': 20}``````