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

遍历嵌套字典匹配布尔值赋值,求更Pythonic实现方案

更Pythonic的嵌套字典赋值实现

问题描述

我们有以下三个数据结构:

  • 嵌套布尔字典 assignments_dict:
assignments_dict = {"first": {'0': True,
                              '1': True},
                    "second": {'0': True,
                               '1': False},
                    }
  • 结果数组 results_array,元素数量与assignments_dict中True的数量完全匹配:
results_array = [10, 11, 12]
  • 待填充的结果字典 results_dict:
results_dict = {"first": {'0': {'output': None},
                          '1': {'output': None}},
                "second": {'0': {'output': None},
                           '1': {'output': None}},
                }

需求是遍历assignments_dict,当对应值为True时,依次取出results_array的元素,赋值到results_dict对应位置的output字段,最终得到:

results_dict = {'first': {'0': {'output': 10},
                          '1': {'output': 11}},
                'second': {'0': {'output': 12},
                           '1': {'output': None}}}

原实现代码:

# counter used to track position in array_outputs
counter = 0
for outer_key in assignments_dict:
    for inner_key in assignments_dict[outer_key]:
        # check if every field in assignments_dict is True/false
        if assignments_dict[outer_key][inner_key]:
            results_dict[outer_key][inner_key]["output"] = results_array[counter]
            # move on to next element in array_outputs
            counter += 1

优化实现

方案1:使用迭代器替代计数器(修改原字典)

这是最贴合需求的Pythonic写法,利用迭代器自动维护取数位置,无需手动操作计数器:

result_iter = iter(results_array)
for outer_key, inner_items in assignments_dict.items():
    for inner_key, is_needed in inner_items.items():
        if is_needed:
            results_dict[outer_key][inner_key]["output"] = next(result_iter)

优势

  • 去掉了冗余的计数器变量,避免了手动增减计数器可能出现的错误
  • 用items()直接遍历字典的键值对,减少了重复的字典索引操作,代码更简洁
  • 变量命名更直观(is_needed替代重复的字典取值),可读性更强

方案2:生成新字典(不修改原数据)

如果需要保留原始的results_dict,可以用嵌套字典推导式生成新的结果字典,更符合函数式编程风格:

result_iter = iter(results_array)
new_results_dict = {
    outer_key: {
        inner_key: {"output": next(result_iter) if is_needed else None}
        for inner_key, is_needed in inner_items.items()
    }
    for outer_key, inner_items in assignments_dict.items()
}

这种方式不会改变原字典,适合需要保留初始数据的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:10:28