chosen

dict 排序
chosen | Jun 15, 2008 1:59:05 PM
Python Cookbook, 2nd Edition
Recipe 5.4. Sorting Keys or Indices Basedon the Corresponding Values

from operator import itemgetter
def dict_items_sorted_by_value(d, reverse=False):
    return sorted(d.iteritems( ), key=itemgetter(1), reverse=reverse)
d={'r':“1“,'w':“2“}
print dict_items_sorted_by_value(d)
#output
#[('r', '1'), ('w', '2')]

变量名不应当用dict,返回结果也不(应当)是dict类型。

Tag: Programming Python

Comment: (no reply)
To post your comment, Please login first.