Dictionary sorting by key length

2019-01-15 20:20发布

问题:

Anyone have any idea how to sort this dictionary by key length?

{
    'http://ccc.com/viewvc/' : [{'type': 'web-servers', 'app': 'Apache', 'ver': '2.2.14'}, {'type': 'operating-systems', 'app': 'Ubuntu', 'ver': None}],    
    'http://bbb.com/' : [{'type': 'web-servers', 'app': 'Apache', 'ver': '2.2.22'}, {'type': 'programming-languages', 'app': 'PHP', 'ver': '5.3.10'}, {'type': 'cms', 'app': 'Drupal', 'ver': None}, {'type': 'operating-systems', 'app': 'Ubuntu', 'ver': None}, {'type': 'javascript-frameworks', 'app': 'jQuery', 'ver': None}, {'type': 'captchas', 'app': 'Mollom', 'ver': None}]
}

Expected output:

{
    'http://bbb.com/' : [{'type': 'web-servers', 'app': 'Apache', 'ver': '2.2.22'}, {'type': 'programming-languages', 'app': 'PHP', 'ver': '5.3.10'}, {'type': 'cms', 'app': 'Drupal', 'ver': None}, {'type': 'operating-systems', 'app': 'Ubuntu', 'ver': None}, {'type': 'javascript-frameworks', 'app': 'jQuery', 'ver': None}, {'type': 'captchas', 'app': 'Mollom', 'ver': None}]
    'http://ccc.com/viewvc/' : [{'type': 'web-servers', 'app': 'Apache', 'ver': '2.2.14'}, {'type': 'operating-systems', 'app': 'Ubuntu', 'ver': None}],    

}

I'm using Python 2.6.

回答1:

newlist = yourdict.items()
sortedlist = sorted(newlist, key=lambda s: len(s[0]))

Will give you a new list of tuples which are sorted by the length of the original keys.



回答2:

Python v2.7+

>>> from collections import OrderedDict
>>> d = {
    'http://ccc.com/viewvc/' : [{'type': 'web-servers', 'app': 'Apache', 'ver': '2.2.14'}, {'type': 'operating-systems', 'app': 'Ubuntu', 'ver': None}],    
    'http://bbb.com/' : [{'type': 'web-servers', 'app': 'Apache', 'ver': '2.2.22'}, {'type': 'programming-languages', 'app': 'PHP', 'ver': '5.3.10'}, {'type': 'cms', 'app': 'Drupal', 'ver': None}, {'type': 'operating-systems', 'app': 'Ubuntu', 'ver': None}, {'type': 'javascript-frameworks', 'app': 'jQuery', 'ver': None}, {'type': 'captchas', 'app': 'Mollom', 'ver': None}]
}
>>> OrderedDict(sorted(d.iteritems(), key=lambda x: len(x[0])))
OrderedDict([('http://bbb.com/', [{'ver': '2.2.22', 'app': 'Apache', 'type': 'web-servers'}, {'ver': '5.3.10', 'app': 'PHP', 'type': 'programming-languages'}, {'ver': None, 'app': 'Drupal', 'type': 'cms'}, {'ver': None, 'app': 'Ubuntu', 'type': 'operating-systems'}, {'ver': None, 'app': 'jQuery', 'type': 'javascript-frameworks'}, {'ver': None, 'app': 'Mollom', 'type': 'captchas'}]), ('http://ccc.com/viewvc/', [{'ver': '2.2.14', 'app': 'Apache', 'type': 'web-servers'}, {'ver': None, 'app': 'Ubuntu', 'type': 'operating-systems'}])])

Earlier Python versions

See OrderedDict for older versions of python.