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

如何通过For Loop从现有数据创建嵌套字典?

解决方案:基于匹配值构建嵌套字典

没问题,我来帮你搞定这个需求!核心思路就是以list_1中的元素作为新字典的外层键,然后遍历dict_1,把内层字典中键2的值匹配的项,归类到对应外层键的下面。

具体实现代码

list_1 = ['aa', 'bb', 'cc']
dict_1 = {
    'key_1': {1: 'data1', 2: 'aa'},
    'key_2': {1: 'data2', 2: 'aa'},
    'key_3': {1: 'data3', 2: 'cc'},
    'key_4': {1: 'data4', 2: 'bb'},
    'key_5': {1: 'data5', 2: 'bb'},
    'key_6': {1: 'data6', 2: 'cc'}
}

# 初始化空的结果字典
result_dict = {}

# 遍历list_1中的每个元素作为外层键
for item in list_1:
    # 给每个外层键初始化一个空字典,用来存放匹配到的项
    result_dict[item] = {}
    # 遍历原字典dict_1的所有键值对
    for outer_key, inner_dict in dict_1.items():
        # 判断内层字典中键2的值是否和当前item匹配
        if inner_dict[2] == item:
            # 匹配成功就添加到结果字典对应位置
            result_dict[item][outer_key] = inner_dict

print(result_dict)

运行结果

执行上面的代码后,你会得到符合预期的嵌套字典:

{
    'aa': {
        'key_1': {1: 'data1', 2: 'aa'},
        'key_2': {1: 'data2', 2: 'aa'}
    },
    'bb': {
        'key_4': {1: 'data4', 2: 'bb'},
        'key_5': {1: 'data5', 2: 'bb'}
    },
    'cc': {
        'key_3': {1: 'data3', 2: 'cc'},
        'key_6': {1: 'data6', 2: 'cc'}
    }
}

优化小技巧(数据量大时更高效)

如果你的dict_1数据量很大,上面的双层循环效率会稍低。可以先把dict_1按内层键2的值做一次分组,这样只需要遍历一次dict_1:

from collections import defaultdict

# 先按内层键2的值分组
temp_group = defaultdict(dict)
for outer_key, inner_dict in dict_1.items():
    temp_group[inner_dict[2]][outer_key] = inner_dict

# 筛选list_1中的元素构建最终结果
result_dict = {item: temp_group[item] for item in list_1 if item in temp_group}

这个方法的逻辑和之前一致,但时间复杂度从O(n*m)降到了O(n+m),数据量大的时候优势会很明显。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:11:38