ITPub博客

首页 > > > Python对字典分别按键(key)和值(value)进行排序

Python对字典分别按键(key)和值(value)进行排序

作者:25minutes 时间:2019-09-29 09:55:29 0 删除 编辑

方法一:

1、对字典按键(key)进行排序

#对字典按键(key)进行排序(默认由小到大)
test_data_0=sorted(dict_data.keys())
 
#输出结果
print(test_data_0) #[3, 6, 7, 8, 10]
 
test_data_1=sorted(dict_data.items(),key=lambda x:x[0])
 
#输出结果
print(test_data_1) #[(3, 11), (6, 9), (7, 6), (8, 2), (10, 5)]


2、对字典按值(value)进行排序

#对字典按值(value)进行排序(默认由小到大)
test_data_2=sorted(dict_data.items(),key=lambda x:x[1])
 
#输出结果
print(test_data_2) #[('8', 2), ('10', 5), ('7', 6), ('6', 9), ('3', 11)]
 
test_data_3=sorted(dict_data.items(),key=lambda x:x[1],reverse=True)
 
#输出结果
print(test_data_3) #[('3', 11), ('6', 9), ('7', 6), ('10', 5), ('8', 2)]


方法二:

import operator
 
#初始化字典
 
dict_data={6:9,10:5,3:11,8:2,7:6}
 
 
 
#按键(key)进行排序
test_data_4=sorted(dict_data.items(),key=operator.itemgetter(0))
test_data_5=sorted(dict_data.items(),key=operator.itemgetter(0),reverse=True)
 
print(test_data_4) #[(3, 11), (6, 9), (7, 6), (8, 2), (10, 5)]
print(test_data_5) #[(10, 5), (8, 2), (7, 6), (6, 9), (3, 11)]
 
 
 
#按值(value)进行排序
 
test_data_6=sorted(dict_data.items(),key=operator.itemgetter(1))
 
test_data_7=sorted(dict_data.items(),key=operator.itemgetter(1),reverse=True)
 
print(test_data_6) #[(8, 2), (10, 5), (7, 6), (6, 9), (3, 11)]
 
print(test_data_7) #[(3, 11), (6, 9), (7, 6), (10, 5), (8, 2)]

Python之眼 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4328/viewspace-3120526/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-17

  • 博文量
    336
  • 访问量
    14923