在 Python 中对词典键和值列表进行排序
当需要对词典中的键和值进行排序时,可以使用“分类”方法。
以下是演示示例 −
示例
my_dict = {'Hi': [1, 6, 3],
'there': [2, 9, 6],
'Mark': [16, 7]}
print("The dictionary is : ")
print(my_dict)
my_result = dict()
for key in sorted(my_dict):
my_result[key] = sorted(my_dict[key])
print("The sorted dictionary is : " )
print(my_result)输出
The dictionary is :
{'Hi': [1, 6, 3], 'there': [2, 9, 6], 'Mark': [16, 7]}
The sorted dictionary is :
{'Hi': [1, 3, 6], 'Mark': [7, 16], 'there': [2, 6, 9]}解释
定义一个词典,并在控制台上显示。
定义一个空词典。
对词典进行迭代,在进行迭代之前对其进行排序。
再次对键进行排序并将其分配给空词典。
在控制台上显示已排序的词典。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP