在 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]}
解釋
定義一個詞典,並在控制檯上顯示。
定義一個空詞典。
對詞典進行迭代,在進行迭代之前對其進行排序。
再次對鍵進行排序並將其分配給空詞典。
在控制檯上顯示已排序的詞典。
廣告