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

如何修改Python代码生成符合预期的按值长度分组字典?

问题描述

现有字典:

dic = {1: 1, 3: 3, 5: 6, 6: 6}

将其反转后得到new_mapping:

new_mapping = {1: [1], 3: [3], 6: [5, 6]}

现有一段循环代码:

for keys, values in new_mapping.items():
    if keys not in new_sort.items():
        if values not in new_sort.items():
            new_sort = new_mapping
            for keys,values in new_sort.items():
                lens = len(values)
                ky = {keys: values}
                lll[lens] = ky

这段代码运行后输出为:

{1: {3: [3]}, 2: {6: [5, 6]}}

但期望的输出是:

{1: {1: [1], 3: [3]}, 2: {6: [5, 6]}}

请问如何修改代码实现该需求?

解决方案

原代码的核心问题是每次处理键值对时,直接用单个键值对字典覆盖lll中对应长度的条目,导致同一长度的前序数据丢失,同时前置的new_sort判断逻辑完全无效(未初始化且判断逻辑错误)。

正确的实现逻辑是:遍历new_mapping的每个键值对,以值的长度作为lll的外层键,将对应的键值对追加到该外层键对应的字典中,而非覆盖。

修改后的代码如下:

new_mapping = {1: [1], 3: [3], 6: [5, 6]}
lll = {}

for key, values in new_mapping.items():
    length = len(values)
    # 若当前长度未在lll中,先初始化空字典
    if length not in lll:
        lll[length] = {}
    # 将当前键值对添加到对应长度的字典内
    lll[length][key] = values

print(lll)

运行后输出结果与期望一致:

{1: {1: [1], 3: [3]}, 2: {6: [5, 6]}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:25:40