这里给出了一个字典,我们的任务是按它们的值排序。该词典中存在两个值,一个是name,另一个是roll。首先,我们使用lambda函数和内置的排序函数按其滚动显示排序列表。
第二,我们按名称和滚动显示排序列表,第三,按其名称显示。
# Initializing list of dictionaries my_list1 = [{ "name" : "Adwaita", "roll" : 100}, { "name" : "Aadrika", "roll" : 234 }, { "name" : "Sakya" , "roll" : 23 }] print ("The list is sorted by roll: ") print (sorted(my_list1, key = lambda i: i['roll']) ) print ("\r") print ("The list is sorted by name and roll: ") print (sorted(my_list1, key = lambda i: (i['roll'], i['name'])) ) print ("\r") print ("The list is sorted by roll in descending order: ") print (sorted(my_list1, key = lambda i: i['roll'],reverse=True) )
输出结果
The list is sorted by roll: [{'name': 'Sakya', 'roll': 23}, {'name': 'Adwaita', 'roll': 100}, {'name': 'Aadrika', 'roll': 234}] The list is sorted by name and roll: [{'name': 'Sakya', 'roll': 23}, {'name': 'Adwaita', 'roll': 100}, {'name': 'Aadrika', 'roll': 234}] The list is sorted by roll in descending order: [{'name': 'Aadrika', 'roll': 234}, {'name': 'Adwaita', 'roll': 100}, {'name': 'Sakya', 'roll': 23}]