如何根据值列表的长度对python字典进行排序

时间:2018-06-14 17:39:54

标签: python python-3.x

作为一个人为的例子,我有一个字典设置如下:

{
  '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()函数按我想要的方式排序?

3 个答案:

答案 0 :(得分:4)

sortedkey一起使用。

<强>实施例

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

Python 3.6+ 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)