Python附加正在附加错误的数据

时间:2019-03-09 14:57:40

标签: python append

我有一个Python程序来获取和检索nba篮球比赛的信息。在我的示例中,有6个游戏正在玩,我获得了所有游戏信息,并将其放入变量gameInfo中。 gameInfo是正确的,当我将其打印出来时,每个游戏都是正确的。但是,当我finalPush [“ games”]。append(gameInfo)时,它会添加最新的gameInfo次数,因此finalPush [“ games”]的最终输出是附加了6次的最后一个游戏。我希望将所有6个游戏的信息都包含在finalPush [“ games”]中。任何帮助将不胜感激,我不知道我在做什么错。

def add_game_info_to_json():
finalPush = {"games": []}
gameInfo = {
    "teamHome": "",
    "teamAway": "",
    "recordHome": "",
    "recordAway": "",
    "colorHome": "",
    "colorAway": "",
    "line": "",
    "overunder": "",
    "homeTextColor": "",
    "awayTextColor": "",
    "homeIndex": "",
    "awayIndex": "",
    "time": ""
}

with open('teamMaster.json') as f:
    data = json.load(f)

i = 0
z = 0

while i < (len(teams_list)/2):
    gameInfo.update(time = game_status_list[i])
    gameInfo.update(teamAway = teams_list[i+z])
    gameInfo.update(recordAway = records_list[i + z])
    gameInfo.update(line = betting_list[i + z])
    for team in data:
        if team == gameInfo["teamAway"]:
            gameInfo.update(colorAway = data[team]["color"])
            gameInfo.update(awayTextColor = data[team]["textColor"])
            gameInfo.update(awayIndex = data[team]["index"])

    z += 1
    gameInfo.update(teamHome = teams_list[i+z])
    gameInfo.update(recordHome = records_list[i + z])
    gameInfo.update(overunder = betting_list[i + z])
    for team in data:
        if team == gameInfo["teamHome"]:
            gameInfo.update(colorHome = data[team]["color"])
            gameInfo.update(homeTextColor = data[team]["textColor"])
            gameInfo.update(homeIndex = data[team]["index"])
    print(gameInfo)
    i += 1
    finalPush["games"].append(gameInfo)
    print(finalPush)

1 个答案:

答案 0 :(得分:1)

您将相同的字典追加6次,并继续更新。

您必须附加一份字典副本:

finalPush["games"].append(gameInfo.copy())