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

示例输入:

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

期望的输出:

{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

其他回答

找到了另一种方法:

import json
print json.dumps(d, sort_keys = True)

乌利希期刊指南: 1. 这也可以对嵌套对象进行排序(谢谢@DanielF)。 2. Python字典是无序的,因此只适用于打印或赋值给STR。

l = dict.keys()
l2 = l
l2.append(0)
l3 = []
for repeater in range(0, len(l)):
    smallnum = float("inf")
    for listitem in l2:
        if listitem < smallnum:
            smallnum = listitem
    l2.remove(smallnum)
    l3.append(smallnum)
l3.remove(0)
l = l3

for listitem in l:
    print(listitem)

有一种简单的方法来整理字典。

根据你的问题,

解决方案是:

c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y

(其中c是你的字典名。)

这个程序给出如下输出:

[(1, 89), (2, 3), (3, 0), (4, 5)]

如你所愿。

另一个例子是:

d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x

给出输出:['Albert', 'Bill', 'John', 'Lucy', 'Peter']

y=sorted(d.values())
print y

给出输出:[18,24,32,36,41]

z=sorted(d.items())
print z

给出输出:

[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]

因此,通过将其更改为键、值和项,您可以像您想要的那样打印。希望这能有所帮助!

正如其他人所提到的,字典本质上是无序的。然而,如果问题只是以有序的方式显示字典,你可以在字典子类中重写__str__方法,并使用这个字典类而不是内置的字典。如。

class SortedDisplayDict(dict):
   def __str__(self):
       return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"


>>> d = SortedDisplayDict({2:3, 1:89, 4:5, 3:0})
>>> d
{1: 89, 2: 3, 3: 0, 4: 5}

注意,这不会改变键的存储方式,当你遍历它们时它们返回的顺序等,只是它们在打印时或在python控制台中显示的方式。

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

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

输出结果为:

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