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?
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:
d.iteritems() instead of d.items() for better memory efficiencycollections.OrderedDict is only available on Python 2.7 and Python 3.2 (and higher)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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With