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"}}]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With