You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按值列表长度对Python字典进行降序排序?

按值列表长度降序排序Python字典

要实现按字典值(整数列表)的长度降序排序,在Python 3.7及以上版本中,由于字典默认保留插入顺序,可通过以下方式实现:

实现代码

# 输入字典
_dict = {
    'owner_1': [320, 203, 123, 32, 923, 12398], 
    'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93, 
               9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83], 
    'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912, 
               9219, 239, 9021092, 9294]
}

# 按值列表长度降序排序并转换为新字典
sorted_dict = dict(sorted(_dict.items(), key=lambda item: len(item[1]), reverse=True))

# 输出结果
print(sorted_dict)

代码说明

  • _dict.items():提取字典的键值对元组列表,每个元组格式为(键, 值列表)
  • sorted(..., key=lambda item: len(item[1]), reverse=True):
    • key=lambda item: len(item[1]):以每个值列表的长度作为排序依据
    • reverse=True:设置为降序排序规则
  • dict(...):将排序后的元组列表转换为有序字典

运行结果

{
    'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93, 
                9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83], 
    'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912, 
                9219, 239, 9021092, 9294], 
    'owner_1': [320, 203, 123, 32, 923, 12398]
}

内容的提问来源于stack exchange,提问作者chan_d12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:39:19