4

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"}}]
key9921
  • 87
  • 1
  • 6
  • Why are you storing these as nested dictionaries rather than a car class with class variables for speed and color? – emsimpson92 Jun 28 '18 at 16:50
  • @emsimpson92 not only it can be an example, but if there is only data (for example DB of a car reseller) building a class is really time/space inefficient – Gsk Jun 28 '18 at 16:53
  • Possible duplicate of [Sort nested dictionary by value, and remainder by another value, in Python](https://stackoverflow.com/questions/4110665/sort-nested-dictionary-by-value-and-remainder-by-another-value-in-python) – ababuji Jun 28 '18 at 16:54
  • Plus if you're serializing/deserializing these values, dictionaries convert to/from json very cleanly with little overhead. So keeping data as nested dictionaries is very clean and efficient in addition to being pythonic. – BowlingHawk95 Jun 28 '18 at 16:54
  • I see. I hadn't considered json – emsimpson92 Jun 28 '18 at 16:55

2 Answers2

5

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

kosnik
  • 2,342
  • 10
  • 23
3

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)))
SamAtWork
  • 455
  • 5
  • 17