也许这很明显,但我如何根据其中的值数对字典进行排序?
就像这样:
{
"2010": [2],
"2009": [4,7],
"1989": [8]
}
会变成这样:
{
"2009": [4,7],
"2010": [2],
"1989": [8]
}
我如何只返回有>的密钥? 1值
"2009": [4,7]
答案 0 :(得分:8)
字典是无序的,因此无法对字典本身进行排序。您可以将字典转换为有序数据类型。在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])))
答案 1 :(得分:2)
标准dict
类型本质上是一个哈希表,不允许用户重新排序其键。但是,您可以使用OrderedDict
:
In [1]: d = {
...: "2010": [2],
...: "2009": [4,7],
...: "1989": [8]
...: }
In [2]: from collections import OrderedDict
In [5]: OrderedDict(sorted(d.items(), key=lambda (k,v):len(v), reverse=True))
Out[5]: OrderedDict([('2009', [4, 7]), ('2010', [2]), ('1989', [8])])
过滤掉短于两个元素的条目:
In [7]: dict((k,v) for k,v in d.items() if len(v) > 1)
Out[7]: {'2009': [4, 7]}