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

示例输入:

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

期望的输出:

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

当前回答

或者用熊猫,

演示:

>>> d={'B':1,'A':2,'C':3}
>>> df=pd.DataFrame(d,index=[0]).sort_index(axis=1)
   A  B  C
0  2  1  3
>>> df.to_dict('int')[0]
{'A': 2, 'B': 1, 'C': 3}
>>> 

See:

这方面的文档 整只熊猫的记录

其他回答

对于CPython/PyPy 3.6,以及任何Python 3.7或更高版本,这很容易做到:

>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{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}

会产生你想要的结果:

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

 sort_dic = {}

 for i in sorted(D1):
     sort_dic.update({i:D1[i]})
 print sort_dic


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

但这并不是正确的方法,因为它可以在不同的字典中显示不同的行为,这是我最近学到的。因此,蒂姆在回答我的问题时提出了一个完美的方法,我在这里分享。

from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))

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

正如其他人所提到的,字典本质上是无序的。然而,如果问题只是以有序的方式显示字典,你可以在字典子类中重写__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控制台中显示的方式。