在 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]}

解釋

  • 定義一個詞典,並在控制檯上顯示。

  • 定義一個空詞典。

  • 對詞典進行迭代,在進行迭代之前對其進行排序。

  • 再次對鍵進行排序並將其分配給空詞典。

  • 在控制檯上顯示已排序的詞典。

更新日期:17-4-2021

392 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告