python: sorting a dict of dicts on a key
python
Solution
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)
Problem
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?