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

Python遍历嵌套字典时如何追加子字典到目标容器获得预期输出

问题原因
  1. 你定义的dict1是单个字典,只能存储一组scale和test键值对,无法容纳多组结果。另外你期望输出的{{...}}属于Python非法格式:字典是不可哈希类型,不能存入集合(set),默认你需要的是列表包裹多字典的结构。
  2. 循环中你始终修改同一个blue_print字典对象,每次赋值都会覆盖上一次的结果,且仅在循环结束后才把最后一次的结果存入dict1,最终只能拿到最后一组值。
修正代码
a = {'test': {'test': 'Test2', 'scale': 'scale4'},
     'test2': {'test': 'test5', 'scale': 'scale44'},
     'test3': {'test': 'Test2', 'scale': 'scale4'}}

# 用列表存储多组字典结果
result = []

for v in a.values():
    # 每次循环生成新的字典,避免覆盖历史值
    current_item = {
        'scale': v.get('scale'),
        'test': v.get('test')
    }
    result.append(current_item)

print(result)

也可以用更简洁的列表推导式实现:

a = {'test': {'test': 'Test2', 'scale': 'scale4'},
     'test2': {'test': 'test5', 'scale': 'scale44'},
     'test3': {'test': 'Test2', 'scale': 'scale4'}}
result = [{'scale': v.get('scale'), 'test': v.get('test')} for v in a.values()]
print(result)
输出结果
[{'scale': 'scale4', 'test': 'Test2'}, {'scale': 'scale44', 'test': 'test5'}, {'scale': 'scale4', 'test': 'Test2'}]

如果你确实需要输出外层为大括号的字符串格式,可以自行调整打印逻辑,该格式仅为展示用,不是合法的Python可直接使用的数据结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:57:00