安迪_963

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

有时有一种需要,求要按字典的值对字典值进行排序:

下面有两种方法

#!/usr/bin/env python
#coding:utf-8
#@Author:Andy

from random import randint

# generate a random dict
dict1 = {x :randint(1, 100) for x in "abczyx"}
print(dict1)
#method 1
# use built in function  sorted ,zip
dict2 = sorted(zip(dict1.values(), dict1.keys()))
print(dict2)

print("*********")
#method 2

dict3 = sorted(dict1.items(), key = lambda x : x[1])
print(dict3)

 

 

 上面这两种方法最终排序完成的都是一个元组,并非字典,如果需要,可以将其还原成字典。

而且定两种方法得出的元组的形式是相反的。但如果这时需要得到键,那这两种方式都是很方便的。

 

posted on 2017-06-07 18:56  Andy_963  阅读(688)  评论(0编辑  收藏  举报