Python程序根据最大值对字典列表进行排序
给定以字典为元素的列表,编写一个Python程序,根据字典的键值对中的最大值对字典进行排序。简单来说,首先将检查列表(即字典)的每个元素,这意味着将比较每个键值对以找到具有最大值的元素。然后,在列表中排序将根据哪个元素包含如此获得的最大值进行。
例子:
Input : test_list = [{1:5, 6:7, 9:1}, {2:6, 9:10, 1:4}, {6:5, 9:3, 1:6}]
Output : [{6: 5, 9: 3, 1: 6}, {1: 5, 6: 7, 9: 1}, {2: 6, 9: 10, 1: 4}]
Explanation : 6 < 7 < 10, is maximum elements ordering.
- 6 is maximum in dictionary having 5, 3, 6 as values in a key-value pair
- 7 is maximum in dictionary having 5, 7, 1 as values in a key-value pair and
- 10 is maximum in dictionary having 6, 10, 4 as values in a key-value pair.
Input : test_list = [{1:5, 6:7, 9:1}, {2:6, 9:10, 1:4}]
Output : [{1: 5, 6: 7, 9: 1}, {2: 6, 9: 10, 1: 4}]
Explanation : 7 < 10,
- 7 is maximum in dictionary having 5, 7, 1 as values in a key-value pair
- 10 is maximum in dictionary having 6, 10, 4 as values in a key-value pair
方法#1:使用values() 、 max()和sort()
在这里,我们使用 sort() 执行就地排序任务,使用 max() 获取最大值,使用 values() 获取值。外部函数作为参数传递以实现所需的功能。
例子:
Python3
# getting max value
def get_max(dicts):
return max(list(dicts.values()))
# initializing list
test_list = [{1: 5, 6: 7, 9: 1}, {2: 6, 9: 10, 1: 4}, {6: 5, 9: 3, 1: 6}]
# printing original list
print("The original list is : " + str(test_list))
# sorting dictionary list by maximum value
test_list.sort(key=get_max)
# printing result
print("Sorted List : " + str(test_list))
Python3
# initializing list
test_list = [{1: 5, 6: 7, 9: 1}, {2: 6, 9: 10, 1: 4}, {6: 5, 9: 3, 1: 6}]
# printing original list
print("The original list is : " + str(test_list))
# sorting dictionary list by maximum value
# one statement sort
res = sorted(test_list, key=lambda dicts: max(list(dicts.values())))
# printing result
print("Sorted List : " + str(res))
输出:
The original list is : [{1: 5, 6: 7, 9: 1}, {2: 6, 9: 10, 1: 4}, {6: 5, 9: 3, 1: 6}]
Sorted List : [{6: 5, 9: 3, 1: 6}, {1: 5, 6: 7, 9: 1}, {2: 6, 9: 10, 1: 4}]
方法#2:使用sorted(), lambda 、 max()和values()
在这里,我们使用 sorted() 和 lambda函数执行排序,以提供单语句过滤而不是调用外部函数。
例子:
蟒蛇3
# initializing list
test_list = [{1: 5, 6: 7, 9: 1}, {2: 6, 9: 10, 1: 4}, {6: 5, 9: 3, 1: 6}]
# printing original list
print("The original list is : " + str(test_list))
# sorting dictionary list by maximum value
# one statement sort
res = sorted(test_list, key=lambda dicts: max(list(dicts.values())))
# printing result
print("Sorted List : " + str(res))
输出:
The original list is : [{1: 5, 6: 7, 9: 1}, {2: 6, 9: 10, 1: 4}, {6: 5, 9: 3, 1: 6}]
Sorted List : [{6: 5, 9: 3, 1: 6}, {1: 5, 6: 7, 9: 1}, {2: 6, 9: 10, 1: 4}]