首页 > 解决方案 > 在循环中添加新的嵌套字典

问题描述

在循环中构建嵌套字典时遇到真正的麻烦。无论我做什么,我都只会得到包含最后一个字典的嵌套字典。代码的一个版本是:

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,而不是每次都添加一个新的键/值对。根本无法理解。有任何想法吗?

标签: pythonloopsdictionarynested

解决方案


推荐阅读