python字典按照key排序_python中字典按key值排序的实现⽅
之前⼩编介绍了字典本⾝不可排序,但按值可以,⼩编也介绍了按value值排序的三种⽅法。sorted()函数可以对数字或字符串进⾏排序,按key排序只是输出的key值的排序列表,使⽤sorted()函数可以对字典按键(key)进⾏排序。本⽂⼩编就向⼤家介绍⽤sorted()函数实现按key值排序的原理和实现实例。
1、sorted()函数
可以对数字(从⼩到⼤。从⼤到⼩)或字符串(ASCII编码)进⾏排序
使⽤语法
sorted(iterable,key,reverse)
2、按key排序
只是输出的key值的排序列表
sorted(d.keys(), reverse=True/False)
3、使⽤实例
对字典按键(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)]
快速排序python实现以上就是python中⽤sorted()函数实现字典按key值排序的使⽤⽅法,希望能帮到你哦~