我想按" date"排序字典列表。如果日期不是字典中的0,那么" uid"。
下面是字典列表
students = [{"name": "Student1", "JoiningDate": 2012, "uid": 5}, {"name": "Student2", "JoiningDate": 2008, "uid":10},
{"name": "Student3", "JoiningDate": 2017, "uid": 1}]
我使用了以下代码,但这是完全错误的。
sorted_set = sorted(set_of_students(key=lambda item:item['JoiningDate']) if item["JoiningDate"] != 0 else (key=lambda item:item['uid']))
请帮忙。
答案 0 :(得分:0)
我假设您希望在结果的末尾聚合日期等于0的字典,按uid
排序。
在此假设下,您可以使用如下的元组键:
students = [{"name": "Student1", "JoiningDate": 2012, "uid": 5},
{"name": "Student2", "JoiningDate": 2008, "uid":10},
{"name": "Student3", "JoiningDate": 2017, "uid": 1},
{"name": "Student4", "JoiningDate": 0, "uid":15},
{"name": "Student5", "JoiningDate": 2010, "uid":6},
{"name": "Student6", "JoiningDate": 0, "uid": 3}]
res = sorted(students, key=lambda x: (x['JoiningDate']==0, x['JoiningDate'], x['uid']))
print(res)
[{'JoiningDate': 2008, 'name': 'Student2', 'uid': 10},
{'JoiningDate': 2010, 'name': 'Student5', 'uid': 6},
{'JoiningDate': 2012, 'name': 'Student1', 'uid': 5},
{'JoiningDate': 2017, 'name': 'Student3', 'uid': 1},
{'JoiningDate': 0, 'name': 'Student6', 'uid': 3},
{'JoiningDate': 0, 'name': 'Student4', 'uid': 15}]