Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: sorting a dict of dicts on a key

Tags:

python

A data structure like this.

{
  'ford': {'count': 3},
  'mazda': {'count': 0},
  'toyota': {'count': 1}
 }

What's the best way to sort on the value of count within the values of the top-level dict?

like image 640
Wells Avatar asked May 14 '26 20:05

Wells


2 Answers

d = {'ford': {'count': 3},
     'mazda': {'count': 0},
     'toyota': {'count': 1}}

>>> sorted(d.items(), key=lambda (k, v): v['count'])
[('mazda', {'count': 0}), ('toyota', {'count': 1}), ('ford', {'count': 3})]

To keep the result as a dictionary, you can used collections.OrderedDict:

>>> from collections import OrderedDict
>>> ordered = OrderedDict(sorted(d.items(), key=lambda (k, v): v['count']))
>>> ordered
OrderedDict([('mazda', {'count': 0}), ('toyota', {'count': 1}), ('ford', {'count': 3})])
>>> ordered.keys()          # this is guaranteed to come back in the sorted order
['mazda', 'toyota', 'ford']
>>> ordered['mazda']        # still a dictionary
{'count': 0}

Version concerns:

  • On Python 2.x you could use d.iteritems() instead of d.items() for better memory efficiency
  • collections.OrderedDict is only available on Python 2.7 and Python 3.2 (and higher)
like image 66
Andrew Clark Avatar answered May 17 '26 09:05

Andrew Clark


A dicitonary is an unordered data structure, so it cannot be sorted. You could create a sorted list (or, in Python 2.7, an OrderedDict) from your dictionary d:

sorted(d.iteritems(), key=lambda item: item[1]["count"])

This list can be used as constructor argument for a collections.OrderedDict.

like image 29
Sven Marnach Avatar answered May 17 '26 08:05

Sven Marnach