程式扎記: [ Python 常見問題 ] How can I sort a dictionary by key?

標籤

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)


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!