字典元素排序

发源:

Zoom.Quiet <[email protected]> 
日期:Mon, 21 May 2007 18:35:44 +0800
当地时间:2007年5月21日(星期一) 下午6时35分

主题:[tip]tip~字典排序 非常经典的需求,一直以为自个儿会的...

题面儿

   1 myDict ={"url12.html":12
   2     ,"url1112.html":212
   3     ,"url346.html":1333
   4     ,"url222.html":12
   5     }

期望按照值的排序进行输出,值有可能一样; 原先以为可以使用外部数组排序后比对输出的,因为值可能重复才发觉不成; 询问 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 开始数组的排序可以指定键位置! 所以:

   1 for k, v in sorted(myDict.items()
   2     , key=lambda x: x[1]
   3     ,reverse=True):
   4     print k,v

就可以获得从大到小的排序字典输出了

要仔细看内置函式哪....

better

"Qiangning Hong" <[email protected]>
日期: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 中广泛使用的:

   1 for k, v in sorted(myDict.items()
   2     , key=lambda x: x[1]
   3     ,reverse=True):
   4     print k,v

PEP265

PEP 265 -- Sorting Dictionaries by Value


反馈

创建 by -- ZoomQuiet [2008-07-01 14:19:42]

Name Password4deL ;) :( X-( B-)

PageCommentData