Python——按键的第 i 个索引值对字典列表进行排序


当需要根据键的“i”索引值对字典列表进行排序时,可以使用“sorted”方法和 lambda 方法。

示例

以下是对此进行演示的示例 -

Open Compiler
my_list = [{"Python" : "Best", "to" : "Code"}, {"Python" : "Good", "to" : "Learn"}, {"Python" : "object", "to" : "cool"}, {"Python" : "oriented", "to" : "language"}] print("The list is : " ) print(my_list) K = "Python" print("The value of K is ") print(K) i = 2 print("The value of i is :") print(i) my_result = sorted(my_list, key = lambda sub: sub[K][i]) print("The resultant list is : ") print(my_result)

输出

The list is :
[{'Python': 'Best', 'to': 'Code'}, {'Python': 'Good', 'to': 'Learn'}, {'Python': 'object', 'to': 'cool'},
{'Python': 'oriented', 'to': 'language'}]
The value of K is
Python
The value of i is :
2
The resultant list is :
[{'Python': 'oriented', 'to': 'language'}, {'Python': 'object', 'to': 'cool'}, {'Python': 'Good', 'to':
'Learn'}, {'Python': 'Best', 'to': 'Code'}]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

结果说明

  • 创建了字典列表,并将其显示在控制台上。

  • 定义了“K”的值,并将其显示在控制台上。

  • 定义了“i”的值,并将其显示在控制台上。

  • 使用“sorted”方法对列表进行排序,并使用 lambda 函数作为键。

  • 将其赋值给一个变量。

  • 此变量显示为控制台上的输出。

更新于: 13-9 月-2021

382 次浏览

开启您的事业

完成该课程即可获得认证

开始
广告