如何按键对字典进行排序?

示例输入:

{2:3, 1:89, 4:5, 3:0}

期望的输出:

{1:89, 2:3, 3:0, 4:5}

当前回答

伙计们,你们把事情搞复杂了……非常简单

from pprint import pprint
Dict={'B':1,'A':2,'C':3}
pprint(Dict)

输出结果为:

{'A':2,'B':1,'C':3}

其他回答

在这里,我找到了一些最简单的解决方案,使用pprint按键对python字典进行排序。 如。

>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99} 
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}

但是当使用pprint时,它将返回排序后的dict

>>> import pprint 
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}

Python字典是无序的。通常,这不是问题,因为最常见的用例是执行查找。

最简单的方法是创建一个集合。OrderedDict以排序顺序插入元素。

ordered_dict = collections.OrderedDict([(k, d[k]) for k in sorted(d.keys())])

如果需要迭代,就像上面其他人建议的那样,最简单的方法是迭代排序的键。的例子,

按键排序打印值:

# create the dict
d = {k1:v1, k2:v2,...}
# iterate by keys in sorted order
for k in sorted(d.keys()):
    value = d[k]
    # do something with k, value like print
    print k, value

获取按键排序的值列表:

values = [d[k] for k in sorted(d.keys())]

注意:对于Python 3.7+,请参见此答案

标准Python字典是无序的(直到Python 3.7)。即使对(键,值)对进行了排序,也不能将它们存储在字典中以保持排序。

最简单的方法是使用OrderedDict,它会记住元素被插入的顺序:

In [1]: import collections

In [2]: d = {2:3, 1:89, 4:5, 3:0}

In [3]: od = collections.OrderedDict(sorted(d.items()))

In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])

不要在意od是如何打印出来的;它会像预期的那样工作:

In [11]: od[1]
Out[11]: 89

In [12]: od[3]
Out[12]: 0

In [13]: for k, v in od.iteritems(): print k, v
   ....: 
1 89
2 3
3 0
4 5

Python 3

对于Python 3用户,需要使用.items()而不是.iteritems():

In [13]: for k, v in od.items(): print(k, v)
   ....: 
1 89
2 3
3 0
4 5
from operator import itemgetter
# if you would like to play with multiple dictionaries then here you go:
# Three dictionaries that are composed of first name and last name.
user = [
    {'fname': 'Mo', 'lname': 'Mahjoub'},
    {'fname': 'Abdo', 'lname': 'Al-hebashi'},
    {'fname': 'Ali', 'lname': 'Muhammad'}
]
#  This loop will sort by the first and the last names.
# notice that in a dictionary order doesn't matter. So it could put the first name first or the last name first. 
for k in sorted (user, key=itemgetter ('fname', 'lname')):
    print (k)

# This one will sort by the first name only.
for x in sorted (user, key=itemgetter ('fname')):
    print (x)

2.7中两个方法的时间比较显示它们实际上是相同的:

>>> setup_string = "a = sorted(dict({2:3, 1:89, 4:5, 3:0}).items())"
>>> timeit.timeit(stmt="[(k, val) for k, val in a]", setup=setup_string, number=10000)
0.003599141953657181

>>> setup_string = "from collections import OrderedDict\n"
>>> setup_string += "a = OrderedDict({1:89, 2:3, 3:0, 4:5})\n"
>>> setup_string += "b = a.items()"
>>> timeit.timeit(stmt="[(k, val) for k, val in b]", setup=setup_string, number=10000)
0.003581275490432745