Python构建嵌套字典时重复值未保存问题求助
问题分析与解决
错误原因
你代码里的核心问题出在strlist.index(n)这个调用上:
list.index()方法的特性是返回第一个匹配元素的索引,而不是当前循环到的元素的真实索引。- 当循环处理第二个"11"时,
strlist.index("11")返回的还是第一个"11"的位置1,而非当前的索引2。这就导致你给weighted_dict[1]重复赋值(虽然值看起来一致),本该生成的键2根本没被创建,最终结果里就少了索引2对应的条目。
修正方案
改用enumerate()函数,它能在循环时同时拿到当前元素的真实索引和元素值,完美解决这个问题:
def order_weight(strng): strlist = strng.split(' ') weighted_dict = {} # 用enumerate获取索引和元素 for idx, n in enumerate(strlist): digtotal = 0 for digit in n: digtotal += int(digit) weighted_dict[idx] = {digtotal: n} print(weighted_dict) order_weight("9999 11 11 22")
运行结果
修正后执行代码,输出就是你预期的结果:{0: {36: '9999'}, 1: {2: '11'}, 2: {2: '11'}, 3: {4: '22'}}
内容的提问来源于stack exchange,提问作者Kyren Lee
相关产品推荐
相关产品推荐

