字典按键长排序

问题描述:

有人知道如何按密钥长度对字典进行排序吗?

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

预期输出:

{
    '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}],    

}

我正在使用Python 2.6.

I'm using Python 2.6.

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

早期的Python版本

有关旧版本的python,请参见 OrderedDict.

Earlier Python versions

See OrderedDict for older versions of python.