Python: sorting dictate dicts on a key

Data structure like this.

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

      

What is the best way to sort the value count

within the top level dictator values?

+3


source to share


6 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 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()

    instead d.items()

    to improve memory efficiency
  • collections.OrderedDict

    only available in Python 2.7 and Python 3.2 (and up)
+11


source


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

.

+2


source


An even cleaner way would be to use itemgetter and then use the value to construct the ordered dict as others suggested.

>>> from operator import itemgetter
>>> sorted(s,key=itemgetter,reverse=True)
['ford', 'toyota', 'mazda']

      

0


source


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})])
>>> 

      

0


source


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, ...)

0


source


If the dict you have is called x, then you can get a list of keys: sorted_x = sorted (x, key = lambda a: x [a] ['count']) where sorted_x: ['mazda', 'toyota' , 'ford']

Then you can print: for i in sorted_x: print x [i]

Result: {'count': 0} {'count': 1} {'count': 3}

0


source







All Articles