对字典键进行排序,其中键也是字典

Kai*_*etz 4 python sorting dictionary python-3.x

我有一个关于如何对这样的字典进行排序的快速问题:

我有的是:

vehicles = {"carA": {"speed": 20, "color": "red"}, "carB": {"speed": 25, "color": "blue"}}
Run Code Online (Sandbox Code Playgroud)

我想要的是一个列表,其中车辆字典按速度的高速排序(carB的速度高于carA的速度,因此carB是列表中的第一个):

vehicles_list = [{"carB": {"speed": 25, color: "blue"}}, {"carA": {"speed": 20, color: "red"}}]
Run Code Online (Sandbox Code Playgroud)

kos*_*nik 5

尝试使用key内置sorted函数的参数

vehicles_list = sorted([{k:v} for k,v in vehicles.items()], 
                       key=lambda x: list(x.values())[0]['speed'],
                       reverse=True)
Run Code Online (Sandbox Code Playgroud)

注意 我已将color您修改dict为a string,除非它是您定义的类型,这是一个错误