Main Content

Sorting a dict in Python

Archive - Originally posted on "The Horse's Mouth" - 2016-04-01 18:24:53 - Graham Ellis

* You cannot sort a dict
* If you sort a list of strings that are digits, you don't get a numeric sort by default

Solutions

* Sort a list of keys
* Specifiy a sort lambda (Python 2 comparator, Python 3 key function) for that list

Example code:

  stuff = {'9': 36, '10': 26, '8': 25, '6': 2}
  
  print "Sorting in NUMERIC order ----------------------- "
  names = stuff.keys()
  names.sort(lambda x,y: int(x)-int(y))
  
  print "Output in NUMERIC order ----------------------- "
  for name in names:
    print name,stuff[name]


Following code fills in the gaps for missing keys:

  print "Filling the 'gaps' ---------------------------- "
  for want in range(int(names[0]),int(names[-1])+1):
    stuff[str(want)] = stuff.get(str(want),0)
  
  print "Output in NUMERIC order ----------------------- "
  for name in range(int(names[0]),int(names[-1])+1):
    print name,stuff[str(name)]


Running that:

  WomanWithCat:apr16 grahamellis$ python od
  Sorting in NUMERIC order -----------------------
  Output in NUMERIC order -----------------------
  6 2
  8 25
  9 36
  10 26
  Filling the 'gaps' ----------------------------
  Output in NUMERIC order -----------------------
  6 2
  7 0
  8 25
  9 36
  10 26
  WomanWithCat:apr16 grahamellis$


Complete source for Python 2 - [here] or for Python 3 [here].

As an alterative, take a look at the OrderedDict class in the collections module.