Python - 按大小对字典进行排序
给定字典列表,按字典大小进行排序。
Input : test_list = [{4:6, 9:1, 10:2, 2:8}, {4:3, 9:1}, {3:9}, {1:2, 9:3, 7:4}]
Output : [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}, {4: 6, 9: 1, 10: 2, 2: 8}]
Explanation : 1 < 2 < 3 < 4, sorted by number of keys of dictionary.
Input : test_list = [{4:3, 9:1}, {3:9}, {1:2, 9:3, 7:4}]
Output : [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}]
Explanation : 1 < 2 < 3, sorted by number of keys of dictionary.
方法 #1:使用 len() + sort()
其中,使用sort()进行排序,使用len()获取字典的大小。
Python3
# Python3 code to demonstrate working of
# Sort Dictionaries by Size
# Using len() + sort()
# function to get length
def get_len(sub):
# return length
return len(sub)
# initializing list
test_list = [{4: 6, 9: 1, 10: 2, 2: 8}, {
4: 3, 9: 1}, {3: 9}, {1: 2, 9: 3, 7: 4}]
# printing original lists
print("The original list is : " + str(test_list))
# performing inplace sort of list
test_list.sort(key=get_len)
# printing result
print("Sorted List : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Dictionaries by Size
# Using sorted() + len() + lambda
# initializing list
test_list = [{4: 6, 9: 1, 10: 2, 2: 8}, {
4: 3, 9: 1}, {3: 9}, {1: 2, 9: 3, 7: 4}]
# printing original lists
print("The original list is : " + str(test_list))
# performing sort using sorted(), lambda for filtering
res = sorted(test_list, key=lambda sub: len(sub))
# printing result
print("Sorted List : " + str(res))
输出:
The original list is : [{4: 6, 9: 1, 10: 2, 2: 8}, {4: 3, 9: 1}, {3: 9}, {1: 2, 9: 3, 7: 4}]
Sorted List : [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}, {4: 6, 9: 1, 10: 2, 2: 8}]
方法 #2:使用 sorted() + len() + lambda
在这里,我们使用sorted()执行排序任务,并使用lambda函数代替外部函数来解决获取长度的问题。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Dictionaries by Size
# Using sorted() + len() + lambda
# initializing list
test_list = [{4: 6, 9: 1, 10: 2, 2: 8}, {
4: 3, 9: 1}, {3: 9}, {1: 2, 9: 3, 7: 4}]
# printing original lists
print("The original list is : " + str(test_list))
# performing sort using sorted(), lambda for filtering
res = sorted(test_list, key=lambda sub: len(sub))
# printing result
print("Sorted List : " + str(res))
输出:
The original list is : [{4: 6, 9: 1, 10: 2, 2: 8}, {4: 3, 9: 1}, {3: 9}, {1: 2, 9: 3, 7: 4}]
Sorted List : [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}, {4: 6, 9: 1, 10: 2, 2: 8}]