python - 在循环中添加新的嵌套字典
问题描述
在循环中构建嵌套字典时遇到真正的麻烦。无论我做什么,我都只会得到包含最后一个字典的嵌套字典。代码的一个版本是:
def choose_games(combo_dict, big_dict, NumT):
global curr_dict
for n in range (1, NumT+1):
comb_games = big_dict[n]
init_scores = [0] * len(comb_games)
curr_dict = dict(zip(comb_games, init_scores))
combo = combo_dict[n]
length = len(combo)
all_dict = {}
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)
每次我运行它时,最后显示 n 的打印函数都会递增并显示 all_dict 的不同值。但它每次只显示一个键。所以当 n = 1 我得到正确的字典,但是当 n = 2 我只得到 n = 2 字典。也就是说,它似乎每次都覆盖 all_dict,而不是每次都添加一个新的键/值对。根本无法理解。有任何想法吗?
解决方案
推荐阅读
- c# - 如何使用 EF Core CosmosDB 提供程序维护唯一值
- reactjs - 我可以使用来自 useSelector 的 useEffect 检查/等待更新吗?
- python - 自动释放python中不再使用的变量的内存
- github - Hexo NeXT 主题类别和标签页面
- python - pandas 中的常见情况图
- python - Scipy最小化约束:两个值之一需要为零
- kubernetes - OpenShift,我如何给自己集群管理员?
- python - 奇怪的多处理麻烦
- javascript - 如何在我的网站上显示实时 Firebase 数据?
- c# - 有没有办法从参数的注释中创建 Blazor 组件文档?