0

Having real trouble building a nested dictionary in a loop. No matter what I do, I only end up with the nested dictionary containing the last dictionary. A version of the code is:

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)

Each time I run it, the print functions at the end show n is incrementing and show a different value of all_dict. But it only shows one key each time. So when n = 1 I get the correct dictionary, but when n=2 I only get the n = 2 dictionary. That is it seems to be overwriting all_dict every time, rather than adding a new key/value pair each time. Can't understand it at all. Any ideas?

MWallace
  • 59
  • 6
  • 3
    look at where you put all_dict = {} – Kenny Ostrom Nov 04 '21 at 14:02
  • 1
    Also, `global` smells -- see e.g. https://stackoverflow.com/questions/19158339/why-are-global-variables-evil – Joshua Voskamp Nov 04 '21 at 14:03
  • Ha! Damn, you are right. How did I miss that? It work now, since I shifted all_dict before the loop. Thanks – MWallace Nov 04 '21 at 14:22
  • Yeah, about globals. I am doing an udemy course on python (only half way through) and they warn about globals. I had issues with getting ouptuts from functions (I know there is only one here), but is best practice to create a list of the returns you want from an output then just pull them out by index after when needed? – MWallace Nov 04 '21 at 14:23

0 Answers0