Python循环构建嵌套字典仅保留最后迭代内容问题求解
问题原因
你的代码核心问题出在all_dict的初始化位置:
all_dict = {}被你放在了for n in range(1, NumT+1)的循环体内部,每次进入新的n的迭代时,都会先把all_dict重置为空字典,之前迭代存储的所有内容都会被清空,所以你每次打印all_dict只能看到当前n对应的单组键值对。- 额外说明:你声明的
global curr_dict完全没有必要,curr_dict是循环内的临时变量,不需要设为全局变量,反而会有变量污染的风险。
修正后的代码
def choose_games(combo_dict, big_dict, NumT): # 把all_dict初始化移到循环外,只创建一次 all_dict = {} for n in range (1, NumT+1): comb_games = big_dict[n] init_scores = [0] * len(comb_games) # 去掉无用的global声明 curr_dict = dict(zip(comb_games, init_scores)) combo = combo_dict[n] length = len(combo) if length == 0: pass else: for m in range(0, length): two_games = combo[m] choice = input(f' Match {m+1}/{length}: {two_games[0]} (1), or {two_games[1]} (2)') while choice.isdigit() == False: print("That is not a number, please enter 1 or 2") choice = input(f' Match {m+1}/{length}: {two_games[0]} (1), or {two_games[1]} (2)') choice = int(choice) if choice not in (1,2): print('That is not 1 or 2. You must type "1" or "2"') choice = int(input(f' Match {m+1}/{length}: {two_games[0]} (1), or {two_games[1]} (2)')) else: print(f'You chose {two_games[choice-1]}') curr_dict[two_games[choice-1]] += 1 print(f' n is {n}') print(f'End dict for tier {n} is {curr_dict}') print(n) all_dict[n] = curr_dict print(all_dict) # 如果需要拿到最终的所有结果,可以加返回值 return all_dict
修正说明
- 仅把
all_dict的初始化位置从循环内部移到循环外部,确保整个函数运行过程中只创建一次all_dict,每次迭代仅新增键值对,不会清空原有内容 - 移除了无用的全局变量声明,避免全局变量意外被其他代码修改的风险
- 可选补充:在函数末尾加return语句可以直接把最终的完整嵌套字典返回给调用方使用
内容的提问来源于stack exchange,提问作者MWallace
相关产品推荐
相关产品推荐

