Python 技巧

1 字典排序 (reference:http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/)

 mydict= {'carl':40, 'alan':2,'bib':1,'danny':3}

  #根据KEY来排序

  for key in sorted(mydict.iterkeys()):
           print "%s: %s" %(key,mydict[key])

 # 根据KEY逆序排列
 for key in sorted(mydict.iterkeys(),reverse=True):
           print "%s: %s" %(key,mydict[key])

 


 #根据VALUE来排列

  for key,value in  sorted(mydict.iteritems(),key=lambda(k,v):(v,k)):
            print "%s:%s" %(key,value)

 #根据VALUE逆序排列

 for key,value in  sorted(mydict.iteritems(),key=lambda(k,v):(-v,k)):
            print "%s:%s" %(key,value)

你可能感兴趣的:(python,Blog)