##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = 字典元素排序 = ##startInc 发源:{{{Zoom.Quiet 日期:Mon, 21 May 2007 18:35:44 +0800 当地时间:2007年5月21日(星期一) 下午6时35分 }}} 主题:[tip][[http://groups.google.com/group/python-cn/browse_thread/thread/1f674f2fe812fc67/b1f034f965d230ff|tip~字典排序]] 非常经典的需求,一直以为自个儿会的... == 题面儿 == {{{#!python 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. The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method. New in version 2.4. }}} 从2.4 开始数组的排序可以指定键位置! 所以:{{{#!python for k, v in sorted(myDict.items() , key=lambda x: x[1] ,reverse=True): print k,v }}} 就可以获得从大到小的排序字典输出了 要仔细看内置函式哪.... == better == {{{ "Qiangning Hong" 日期:Mon, 21 May 2007 18:53:14 +0800 当地时间:2007年5月21日(星期一) 下午6时53分 }}} a better and quicker way: {{{ from operator import itemgetter sorted(myDict.iteritems(), key=itemgetter(1), reverse=True) }}} :) == FP == 更加通用的,在 exoweb.com 中广泛使用的: {{{#!python for k, v in sorted(myDict.items() , key=lambda x: x[1] ,reverse=True): print k,v }}} == PEP265 == `PEP 265 -- Sorting Dictionaries by Value` * http://www.python.org/dev/peps/pep-0265/ * '''[[http://openbookproject.googlecode.com/svn/trunk/PEPs_zh/pep-0265_zh.txt|OBP:pep-0265_zh]]''' ##endInc ---- '''反馈'''