Python: sorting dictate dicts on a key
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 store the result as a dictionary, you can use 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 refers to:
- In Python 2.x, you can use
d.iteritems()
insteadd.items()
to improve memory efficiency -
collections.OrderedDict
only available in Python 2.7 and Python 3.2 (and up)
source to share
Discriminate is an unordered data structure, so it cannot be sorted. You can create a sorted list (or in Python 2.7, OrderedDict
) from your dictionary d
:
sorted(d.iteritems(), key=lambda item: item[1]["count"])
This list can be used as a constructor argument for collections.OrderedDict
.
source to share
If you want to sort the dictionary by some element in the value, the result you cannot save as a dict because in the dict the order of adding the element is not saved. Fot that you have to use OrderedDict. One solution after sorting generates an OrderedDict from a list of (key, value) tuples.
>>> collections.OrderedDict(sorted(d.iteritems(),key=lambda x:x[1]["count"],reverse=True))
OrderedDict([('ford', {'count': 3}), ('toyota', {'count': 1}), ('mazda', {'count': 0})])
>>>
source to share
I think dict is a hash tableso it cannot be sorted. Try to keep the sorted values in a list that can be sorted:
l = []
for x in sorted(dictionary.keys()):
l.append([dictionary[x]])
If you really want to keep the keys, perhaps add them to the list. Just make sure that when accessing the list, even the indices (0,2,4, ...) are keys and the odd indices are values (1,3,5, ...)
source to share