dict={"Student Id":{
"Name":"student name",
"tests":{"test1":["mark","grade","time"],
"test2":["mark","grade","time"],
"test3":[],
"test4":["mark","grade","time"]}}}
我想将此字典的“tests”到“test4”列表排序到“test3”空列表中,“test4”是空列表。
我尝试交换值,但如果我在“测试”中添加更多键值如何排序?
dict={"Student Id":{
"Name":"student name",
"tests":{"test1":["mark","grade","time"],
"test2":["mark","grade","time"],
"test3":["mark","grade","time"],
"test4":[]}}}
整理后这就是我所期待的
由于您希望空列表排在最后,并且空列表为 false(值为 0),因此您可以使用
operator.not_
作为键函数对 dict 值进行排序,以便空列表获得更大的键值 1,并压缩使用原始键对值进行排序以进行更新:
from operator import not_
tests = d['Student Id']['tests']
tests.update(dict(zip(tests, sorted(tests.values(), key=not_))))