`
zhouzaibao
  • 浏览: 291609 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

字典的排序

阅读更多

      在使用python中的字典存储key/value值的时候,因为当中的存储是无需的,而在输出的时候需要对输出结果进行排序。这个就是sorted的用武之地。
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 (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.
New in version 2.4.

而对于字典的操作见实例:

一:按照key进行排序

strings={'a':2,'b':3}
sorted(strings.iteritems(),key=lambda d:d[0],reverse=True)
#outout [('b', 3), ('a', 2)]

 

二:按照value进行排序

strings={'a':5,'z':1,'b':7}
sorted(strings.iteritems(),key=lambda d:d[1])
#output [('z', 1), ('a', 5), ('b', 7)]
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics