這個博客上對此有很多討論,列出2篇較好的:
http://hi.baidu.com/jrckkyy/blog/item/021849ed8a01e14479f05530.html
http://hi.baidu.com/jrckkyy/blog/item/183933cb3e5c54f653664f12.html
複製一段我覺得以後用得上的
- # 演示對字典數據進行排序
- sampledict_str = {'blue':'[email protected]',
- 'allen':'[email protected]',
- 'sophia':'[email protected]',
- 'ceen':'[email protected]'}
- print sampledict_str
- # 按照key進行排序
- print sorted(sampledict_str.items(), key=lambda d: d[0])
- # 按照value進行排序
- print sorted(sampledict_str.items(), key=lambda d: d[1])