python中字典按key值排序的实现方法

2023-12-14 10:32:23网络知识悟空

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=lambdax:x[0])

#输出结果

print(test_data_1)#[(3,11),(6,9),(7,6),(8,2),(10,5)]

以上就是python中用sorted()函数实现字典按key值排序的使用方法,希望能帮到你哦~更多Python学习教程请关注IT培训机构:筋斗云。

发表评论: