按每个键下的值数对字典进行排序

AWE*_*AWE 0 python dictionary

也许这很明显,但我如何根据其中的值来对字典进行排序?

喜欢这样:

{
    "2010": [2],
    "2009": [4,7],
    "1989": [8]
}
Run Code Online (Sandbox Code Playgroud)

会成为这样的:

{   
    "2009": [4,7],
    "2010": [2],
    "1989": [8]
}
Run Code Online (Sandbox Code Playgroud)

我怎么才会返回有> 1值的键

 "2009": [4,7]
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 9

字典是无序的,因此无法对字典本身进行排序.您可以将字典转换为有序数据类型.在Python 2.7或更高版本中,您可以使用collections.OrderedDict:

from collections import OrderedDict
d = {"2010": [2], "2009": [4,7], "1989": [8]}
ordered_d = OrderedDict(sorted(d.viewitems(), key=lambda x: len(x[1])))
Run Code Online (Sandbox Code Playgroud)