2016年11月25日 星期五

[ Python 常見問題 ] How can I sort a dictionary by key?

Source From Here
Question
What would be a nice way to go from {2:3, 1:89, 4:5, 3:0} to {1:89, 2:3, 3:0, 4:5}? I checked some posts but they all use the "sorted" operator that returns tuples.

How-To
Standard Python dictionaries are unordered. Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering. The easiest way is to use OrderedDict, which remembers the order in which the elements have been inserted:
>>> import collections
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> od = collections.OrderedDict(sorted(d.items()))
>>> od
OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])

>>> for k, v in d.iteritems():
... print "(%d/%d)" % (k, v)
...
(1/89)
(2/3)
(3/0)
(4/5)


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...