怎样才能从"{2:3,1:89,4:5,3:0}"变成"{1:89,2:3,3:0,4:5}"?
我查看了一些帖子,但他们都使用了返回图元的"排序"操作符。
标准的 Python 字典是无序的。即使你对(key,value)对进行了排序,你也不能以一种保留排序的方式将它们存储在dict
中。
最简单的方法是使用 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用户,需要使用.items()
而不是.iteritems()
。
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
词典本身并没有有序的项目,如果你想把它们等打印成某种顺序,这里有一些例子。
在Python 2.4及以上版本中:
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
for key in sorted(mydict):
print "%s: %s" % (key, mydict[key])
给予。
alan: 2
bob: 1
carl: 40
danny: 3
(Python 2.4以下:)
keylist = mydict.keys()
keylist.sort()
for key in keylist:
print "%s: %s" % (key, mydict[key])
源于此。http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
正如其他人所提到的,字典本身是无序的。 然而,如果问题仅仅是以有序的方式显示的字典,你可以在一个字典子类中覆盖__str__
方法,并使用这个字典类而不是内置的dict
。 例如。
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}
注意,这并没有改变键的存储方式,也没有改变当你遍历它们时它们的返回顺序等等,只是改变了它们用 print
或在 python 控制台上的显示方式。