代码改变世界

使用sorted对Dict进行Value排序

2008-02-09 13:46  Jaypei  阅读(809)  评论(1编辑  收藏  举报
sdict = {'w':6,'d':9,'b':2,'m':7,'q':1,'x':8}

print sdict

#根据key排序返回列表
sorted(sdict.items())
#根据value排序返回列表
sorted(sdict.items(),key=lambda d:d[1])

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

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 (described in section 3.6.4).

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: "cmp=lambda x,y: cmp(x.lower(), y.lower())"

key specifies a function of one argument that is used to extract a comparison key from each list element: "key=str.lower"

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.