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

2024-04-23 10:21:56 发布

您现在位置:Python中文网/ 问答频道 /正文

作为一个人为的例子,我有一本字典,它是这样设置的:

{
  'a': ['a', 'b'],
  'b': ['a', 'b', 'c'],
  'c': ['a', 'b', 'c', 'd']
}

我想按列表的长度(即每个条目的值)按降序对字典进行排序,因此结果应该是:

^{pr2}$

我试过这样做:

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()函数按我想要的方式排序,我需要做些什么?在


Tags: ofthenone列表len字典排序items
2条回答

您可以使用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)

或者,你可以不使用听写理解,就像阿兰·菲所说:

^{pr2}$

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) )

输出:

^{pr2}$

如果想维持秩序。

import collections
d = collections.OrderedDict(sorted(d.items(), key= lambda x: len(x[1]), reverse=True))
print( d )

使用^{}

{{1}如果你想使用^ 1}的话。您可以使用key对第一个dict中的项目进行排序。在

代码

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)

输出

^{pr2}$

python3.6+dict是有序的

尽管,如果使用python3.6+,插入顺序将保留为dict。这是特定于CPython实现的,它将仅是一个official language feature starting at version 3.7。在

代码

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)

输出

{'c': ['a', 'b', 'c', 'd'], 'b': ['a', 'b', 'c'], 'a': ['a', 'b']}

相关问题 更多 >