对字典键进行排序,其中键也是字典(Sort dictionary keys where the key is also a dictionary)
我只是一个关于如何对这样的字典进行排序的快速问题:
我所拥有的是:
vehicles = {"carA": {"speed": 20, "color": "red"}, "carB": {"speed": 25, "color": "blue"}}我想要的是一个列表,其中车辆字典按速度的高速排序(carB的速度高于carA的速度,因此carB是列表中的第一个):
vehicles_list = [{"carB": {"speed": 25, color: "blue"}}, {"carA": {"speed": 20, color: "red"}}]I have just a quick question about how to sort a dictionary like this:
What I have is:
vehicles = {"carA": {"speed": 20, "color": "red"}, "carB": {"speed": 25, "color": "blue"}}What I want is a list where the vehicle dictionary is sorted by the high of the speed (the speed of carB is higher than that of carA so carB is the first one in the list):
vehicles_list = [{"carB": {"speed": 25, color: "blue"}}, {"carA": {"speed": 20, color: "red"}}]最满意答案
尝试使用内置sorted函数的key参数
vehicles_list = sorted([{k:v} for k,v in vehicles.items()], key=lambda x: list(x.values())[0]['speed'], reverse=True)注意我已将dict color修改为string ,除非它是您定义的类型,这是一个错误
Try using the key argument of the build-in sorted function
vehicles_list = sorted([{k:v} for k,v in vehicles.items()], key=lambda x: list(x.values())[0]['speed'], reverse=True)NOTE I have modified color in your dict to be a string, unless it is a type defined by you it is an error
更多推荐
发布评论