key9921
key9921

Reputation: 87

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"}}]

Upvotes: 4

Views: 137

Answers (2)

SamAtWork
SamAtWork

Reputation: 465

you could do something like the following:

import operator
list_of_dicts = list(vehicles)
list_of_dicts.sort(key=operator.itemgetter('speed'), reverse=True)

Another solution

from collections import OrderedDict 
order_dic = list(OrderedDict(sorted(dic.items(), key=lambda x: x[1]['speed'], reverse=True)))

Upvotes: 3

kosnik
kosnik

Reputation: 2424

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

Upvotes: 5

Related Questions