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

Python如何使用循环创建带嵌套多键值对的字典

报错原因

  • 你没有预先为外层字典的键创建对应的空内层字典,直接对dictionary[str(key+1)]的子键赋值时,Python找不到外层的'1'键就会抛出KeyError
  • 现有代码的索引逻辑错误,每次循环都只读取attributes的前5个元素,无法为第二个包裹匹配后续的属性值

可行实现代码

基础写法(逻辑清晰易调试)

# 初始化空字典
result_dict = {}
# 单个包裹的属性数量
attr_per_pkg = len(measure_without_duplicates)

for pkg_index, pkg_number in enumerate(number):
    # 先为当前包裹创建空的内层属性字典
    result_dict[pkg_number] = {}
    # 计算当前包裹对应属性在attributes列表中的起始偏移量
    attr_start = pkg_index * attr_per_pkg
    # 遍历度量键,匹配对应的属性值
    for i, measure_key in enumerate(measure_without_duplicates):
        result_dict[pkg_number][measure_key] = attributes[attr_start + i]

简洁写法(利用zip打包生成内层字典)

result_dict = {}
attr_per_pkg = len(measure_without_duplicates)

for pkg_index, pkg_number in enumerate(number):
    start = pkg_index * attr_per_pkg
    end = start + attr_per_pkg
    # 直接将度量键和对应属性切片打包为字典
    result_dict[pkg_number] = dict(zip(measure_without_duplicates, attributes[start:end]))

代码说明

所有索引都是动态计算的,不需要手动切分attributes列表,只要attributes长度随包裹数量同步增长(永远是len(measure_without_duplicates) * len(number)),代码就可以正常运行,完全适配爬虫的动态场景。如果需要外层键为字符串格式,只需要把result_dict[pkg_number]改为result_dict[str(pkg_number)]即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:57:02