[python]对字典进行排序

时间:2021-07-18 20:45:19

myDict ={"url12.html":12
     ,"url1112.html":212
    ,"url346.html":1333
    ,"url222.html":12
...}
期望按照值的排序进行输出,值有可能一样;
原先以为可以使用外部数组排序后比对输出的,因为值可能重复才发觉不成;
询问 xyb,dreamingk 才知道,原来有内置函式支持的!
"""sorted( iterable[, cmp[, key[, reverse]]])
    Return a new sorted list from the items in iterable. Theoptional
arguments cmp, key, and reverse have the same meaning as those forthe
list.sort() method. New in version 2.4.
"""
从2.4 开始数组的排序可以指定键位置!
所以:
for k, v in sorted(myDict.items(), key=lambda x: x[1],reverse=True):
    print k,v

就可以获得从大到小的排序字典输出了
来自:http://hi.baidu.com/sleepymole/blog/item/480a1c466400d10b6b63e587.html