构建以国家为键的嵌套字典时迭代覆盖值问题求解
问题原因
你这段代码的核心问题是所有国家对应的子字典都引用了同一个d_temp对象。字典属于可变数据类型,当你在循环中修改d_temp的键值对时,所有已经赋值给dd[c]的条目都会同步变化——因为它们本质上指向内存中的同一个字典。
解决方法
方法1:循环内新建子字典(最直观)
把子字典的创建放到循环内部,每次迭代都生成一个全新的字典对象,避免引用复用:
countries = {'Portugal', 'US'} score = {'Portugal': 88.0, 'US': 86.20} year = {'Portugal': 2014, 'US': 2013 } price ={'Portugal': 26.77, 'US': 36.58 } # 补充示例数据(根据实际情况替换) d1 = {'Portugal': 'Port', 'US': 'Cabernet Sauvignon'} d5 = {'Portugal': 'Balanced', 'US': 'Rich'} dd = {} for c in countries: d_temp = { 'Variety': d1[c], 'Year': year[c], 'Price': price[c], 'Points': score[c], 'Adjective': d5[c] } dd[c] = d_temp
方法2:用字典推导式简化代码
如果追求简洁,可以直接用字典推导式一步生成嵌套字典:
countries = {'Portugal', 'US'} score = {'Portugal': 88.0, 'US': 86.20} year = {'Portugal': 2014, 'US': 2013 } price ={'Portugal': 26.77, 'US': 36.58 } d1 = {'Portugal': 'Port', 'US': 'Cabernet Sauvignon'} d5 = {'Portugal': 'Balanced', 'US': 'Rich'} dd = { c: { 'Variety': d1[c], 'Year': year[c], 'Price': price[c], 'Points': score[c], 'Adjective': d5[c] } for c in countries }
方法3:复制模板字典(兼容原代码思路)
如果一定要保留原代码中“模板字典”的思路,每次循环时复制一份模板,避免修改原模板影响所有条目:
countries = {'Portugal', 'US'} score = {'Portugal': 88.0, 'US': 86.20} year = {'Portugal': 2014, 'US': 2013 } price ={'Portugal': 26.77, 'US': 36.58 } d1 = {'Portugal': 'Port', 'US': 'Cabernet Sauvignon'} d5 = {'Portugal': 'Balanced', 'US': 'Rich'} dd = {key: None for key in countries} # 创建模板字典 template = dict.fromkeys(["Variety","Year","Price","Points","Adjective"]) for c in countries: # 每次复制新的字典对象 d_temp = template.copy() d_temp['Variety'] = d1[c] d_temp['Year'] = year[c] d_temp['Price'] = price[c] d_temp['Points'] = score[c] d_temp['Adjective'] = d5[c] dd[c] = d_temp
内容的提问来源于stack exchange,提问作者Branden Nevius
相关产品推荐
相关产品推荐

