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

示例输入:

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

期望的输出:

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

当前回答

我的建议是这样的,因为它允许你在添加项和将来可能需要添加项时对字典排序或保持字典排序:

从头开始构建词典。有第二个数据结构,一个包含键列表的列表。bisect包有一个insort函数,允许插入到一个排序的列表中,或者在完全填充字典后对列表进行排序。现在,当您迭代字典时,您将迭代列表以按顺序访问每个键,而不用担心字典结构的表示(它不是为排序而设计的)。

其他回答

这里已经有很多答案展示了对Python字典进行排序的流行方法。我想我应该为那些从谷歌来到这里寻找非标准想法的人添加一些不太明显的方法。

样本字典:d = {2: ' c ', 1: ' b ', 0: ' a ', 3: ' d '}

字典理解

# Converts to list, sorts, re-converts to dict
{k: v for k, v in sorted(list(d.items()))}

使用λ

排序并不总是按照严格的升序或降序进行。对于更多的条件排序,使用上述方法结合lamdas:

{k: v for k, v in sorted(d.items(), key=lambda v: ord(v[1]))}

更多的例子

这个帖子已经有足够多的好例子了。有关更多示例,以及边缘情况和奇怪情况,请参阅这篇关于Python中字典排序的文章。

简单:

d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())

for k,v in sd:
    print k, v

输出:

1 89
2 3
3 0
4 5

在Python 3中。

>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
    print (key, D1[key])

给了

1 89
2 3
3 0
4 5

注意:对于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

我认为最简单的事情是按键对字典进行排序,并将排序的键:值对保存在一个新的字典中。

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be neccessary
        dict2[key] = dict1[key]

更清楚地说:

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted     values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be  neccessary
        value = dict1[key]
        dict2[key] = value