Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dictionary keys where the key is also a dictionary

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"}}]
like image 748
key9921 Avatar asked Jan 27 '23 20:01

key9921


1 Answers

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

like image 178
kosnik Avatar answered Jan 30 '23 11:01

kosnik