如何对嵌套的Python字典进行排序?

如果您有以下格式的字典:

{
   'KEY1':{'name':'foo','data':1351,'completed':100},
   'KEY2':{'name':'bar','data':1541,'completed':12},
   'KEY3':{'name':'baz','data':58413,'completed':18}
}

而且,您想要按升序对每个条目中完成的键进行排序,则可以将排序函数与lambda一起使用,该lambda指定用于对数据进行排序的键。例如,

my_collection = {
   'KEY1':{'name':'foo','data':1351,'completed':100},
   'KEY2':{'name':'bar','data':1541,'completed':12},
   'KEY3':{'name':'baz','data':58413,'completed':18}
}
sorted_keys = sorted(my_collection, key=lambda x: (my_collection[x]['completed']))
print(sorted_keys)

这将给出输出:

['KEY2', 'KEY3', 'KEY1']