对字典键进行排序,其中键也是字典(Sort dictionary keys where the key is also a dictionary)

编程入门 行业动态 更新时间:2024-10-21 09:31:55
字典键进行排序,其中键也是字典(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

更多推荐

本文发布于:2023-08-05 08:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1428921.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   Sort   dictionary   keys   key

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!