Python – 根據大小對字典排序
如果需要按大小對字典進行排序,則需要定義一個方法,該方法採用一個引數並使用“len”來決定輸出。
下面是對此方法的演示:-
示例
def get_len(element):
return len(element)
my_dict = [{24: 56, 29: 11, 10: 22, 42: 28}, {54: 73, 59: 11}, {13: 39}, {31: 22, 59: 73, 57: 44}]
print("The dictionary is :")
print(my_dict)
my_dict.sort(key=get_len)
print("The result is :")
print(my_dict)輸出
The dictionary is :
[{24: 56, 29: 11, 10: 22, 42: 28}, {54: 73, 59: 11}, {13: 39}, {31: 22, 59: 73, 57: 44}]
The result is :
[{13: 39}, {54: 73, 59: 11}, {31: 22, 59: 73, 57: 44}, {24: 56, 29: 11, 10: 22, 42: 28}]說明
定義名為“get_len”的方法,該方法採用元素作為引數,並返回元素長度作為輸出。
定義了一個字典列表,並在控制檯上顯示。
字典已排序,並且關鍵已指定為先前定義的方法。
這是在控制檯上顯示的輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP