[Python] Python Nested Dictionary Set Value [duplicate]

Discussão em 'Python' iniciado por Stack, Junho 8, 2025.

  1. Stack

    Stack Membro Participativo

    I'm making a Yahtzee game, where 3X means "three of a kind", F means 'full house', etc. I am storing the player scores in a nested dictionary called gamedata, that I have made using the code below.

    I want to set player 0's 3X value to 10 which I think can be done with gamedata[0]["3X"] = 10 but this sets all 3X values for all players to 10, not just player 0. See the output below. Why does this happen with this dictionary? I just want to set player 0's 3X value, not all players 3X values, like the code currently does. See the code below. Any help is appreciated.

    userscores = {
    "1": 0,
    "2": 0,
    "3": 0,
    "4": 0,
    "5": 0,
    "6": 0,
    "S": 0,
    "1X": 0,
    "2X": 0,
    "3X": 0,
    "4X": 0,
    "MS": 0,
    "DS": 0,
    "F": 0,
    "G": 0,
    "C": 0,
    "T": 0
    }
    numberofplayers = 3
    gamedata = {}

    for i in range(numberofplayers):
    gamedata = userscores

    gamedata[0]["3X"] = 10 # This doesn't work as intended

    print(gamedata)


    Output:

    {0: {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, 'S': 0, '1X': 0, '2X': 0, '3X': 10, '4X': 0, 'MS': 0, 'DS': 0, 'F': 0, 'G': 0, 'C': 0, 'T': 0}, 1: {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, 'S': 0, '1X': 0, '2X': 0, '3X': 10, '4X': 0, 'MS': 0, 'DS': 0, 'F': 0, 'G': 0, 'C': 0, 'T': 0}, 2: {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, 'S': 0, '1X': 0, '2X': 0, '3X': 10, '4X': 0, 'MS': 0, 'DS': 0, 'F': 0, 'G': 0, 'C': 0, 'T': 0}}

    Continue reading...

Compartilhe esta Página