1

I have a small script in Python with a dictionary same as follows:

d = {'category_1' : ['a', 'b'], 
'category_2' : ['c', 'd', 'e'],
'category_3' : ['z']}

How can I sort it based on number of values in list? I want it looks like:

d = {'category_3' : ['z'], 
'category_1' : ['a', 'b'], 
'category_2' : ['c', 'd', 'e']}
Freak
  • 6,786
  • 5
  • 36
  • 54
5w0rdf1sh
  • 451
  • 1
  • 4
  • 9

1 Answers1

7

Dictionaries in Python are orderless.

In order to actually store ordering, you will need to either have a list of tuples, or use a collections.OrderedDict().

>>> from collections import OrderedDict
>>> OrderedDict(sorted(d.items(), key=lambda item: len(item[1])))
OrderedDict([('category_3', ['z']), ('category_1', ['a', 'b']), ('category_2', ['c', 'd', 'e'])])

The ordering is achieved here by using the sorted() built-in, with a simple key function.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183