根据列表中的项目数排序Python字典

5w0*_*1sh 1 python sorting algorithm

我在Python中有一个小脚本,其字典与如下相同:

d = {'category_1' : ['a', 'b'], 
'category_2' : ['c', 'd', 'e'],
'category_3' : ['z']}
Run Code Online (Sandbox Code Playgroud)

如何根据列表中的值数对其进行排序?我希望它看起来像:

d = {'category_3' : ['z'], 
'category_1' : ['a', 'b'], 
'category_2' : ['c', 'd', 'e']}
Run Code Online (Sandbox Code Playgroud)

Gar*_*tty 7

Python中的字典是无序的.

为了实际存储排序,您需要有一个元组列表,或使用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'])])
Run Code Online (Sandbox Code Playgroud)

排序是通过使用这里实现sorted()内置的,用一个简单的key功能.