作为一个人为的例子,我有一个字典设置如下:
{
'a': ['a', 'b'],
'b': ['a', 'b', 'c'],
'c': ['a', 'b', 'c', 'd']
}
我想按照列表的长度(每个条目的值)按降序对字典进行排序,因此结果应为:
{
'c': ['a', 'b', 'c', 'd'],
'b': ['a', 'b', 'c'],
'a': ['a', 'b']
}
我试过这样的事情:
sorted_functions = sorted(
functions.items(), # Sort the actual items of the dictionary
key=len( # Sort on the length of
operator.itemgetter( # the value of the entry, which is
slice(0, None) # a list slice of the whole list
)
),
reverse=True # Sort the values in descending order
)
然而,我收到此错误:
TypeError: object of type 'operator.itemgetter' has no len()
在REPL中,我尝试了以下内容:
>>> d = { 'a': ['a'], 'b': ['a', 'b'] }
>>> itemgetter(slice(0, None))(d['a'])
['a']
>>> len(itemgetter(slice(0, None))(d['a']))
1
>>> itemgetter(slice(0, None))(d['b'])
['a', 'b']
>>> len(itemgetter(slice(0, None))(d['b']))
2
...所以我能够获得列表的长度,但在sorted()
函数中,它不起作用。
我需要做些什么才能让sorted()
函数按我想要的方式排序?
答案 0 :(得分:4)
将sorted
与key
一起使用。
<强>实施例强>
d = {
'a': ['a', 'b'],
'b': ['a', 'b', 'c'],
'c': ['a', 'b', 'c', 'd']
}
print( sorted(d.items(), key= lambda x: len(x[1]), reverse=True) )
<强>输出:强>
[('c', ['a', 'b', 'c', 'd']), ('b', ['a', 'b', 'c']), ('a', ['a', 'b'])]
如果想维持订单。
import collections
d = collections.OrderedDict(sorted(d.items(), key= lambda x: len(x[1]), reverse=True))
print( d )
答案 1 :(得分:2)
OrderedDict
如果您希望订购dict
,则应使用OrderedDict
。您可以使用key
对第一个from collections import OrderedDict
d = {
'a': ['a', 'b'],
'b': ['a', 'b', 'c'],
'c': ['a', 'b', 'c', 'd']
}
ordered_d = OrderedDict(sorted(d.items(), key=lambda i: -len(i[1])))
print(ordered_d)
中的项目进行排序。
OrderedDict([('c', ['a', 'b', 'c', 'd']), ('b', ['a', 'b', 'c']), ('a', ['a', 'b'])])
dict
dict
已订购但是,如果使用Python 3.6+,则会为d = {
'a': ['a', 'b'],
'b': ['a', 'b', 'c'],
'c': ['a', 'b', 'c', 'd']
}
ordered_d = dict(sorted(d.items(), key=lambda i: -len(i[1])))
print(ordered_d)
保留有序的插入。这是CPython实现特有的,只有official language feature starting at version 3.7。
{'c': ['a', 'b', 'c', 'd'], 'b': ['a', 'b', 'c'], 'a': ['a', 'b']}
{{1}}
答案 2 :(得分:0)
您可以使用lambda
。喜欢:
my_dict = {
'a': ['a', 'b'],
'b': ['a', 'b', 'c'],
'c': ['a', 'b', 'c', 'd']
}
sorted_list = sorted(my_dict.items(), key= lambda value: len(value[1]), reverse=True) #you will get a sorted list,reverse=True will bring longer lists to appear first
print(sorted_list)
sorted_dict = {x[0]:x[1] for x in sorted_list} #convert your sorted list into dictionary
print(sorted_dict)
或者你可以在不使用字典理解的情况下制作它,因为Aran-Fey说:
sorted_dict = dict(sorted_list)