字典按键长排序 [英] Dictionary sorting by key length

查看:97
本文介绍了字典按键长排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于字典按键长排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆