You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python嵌套字典添加元素时所有键同步更新,如何修复?

问题根源与修复方案

问题出在这行代码:

team_dictionary = dict.fromkeys(teamlst, [])

dict.fromkeys方法的特性是:它会把第二个参数的同一个对象引用绑定给所有生成的键。因为列表是可变对象,所以你后续对任何一个键对应的列表执行append操作时,所有键的列表都会同步变化——它们本质上指向内存中的同一个列表。

修复方法

把上面那行代码替换成字典推导式,让每个键都对应一个全新的空列表:

team_dictionary = {key: [] for key in teamlst}

修改后的完整代码

import copy
    
teamdict = {1:{},2:{},3:{},4:{},5:{}}
teamlst = []
matchlst = [1,2,3,4,5]
lst = [[1,5,0],[1,0,3],[2,3,0],[2,0,1],[3,0,6],[3,0,1],[4,0,1],[4,0,5],[5,0,8]]
for i in matchlst:
    for j in lst:
        if i == j[0]:
            teamlst.append(j[2])
        elif len(teamlst)>0 and i != j:
            continue
        else:
            pass
    teamlst = set(teamlst)
    teamlst = list(teamlst)
    teamlst.sort()
    # 替换成字典推导式
    team_dictionary = {key: [] for key in teamlst}
    teamdict[i] = team_dictionary
    teamlst.clear()
print(teamdict)
dic = copy.deepcopy(teamdict)

for i in lst:
    dic[i[0]][i[2]].append(i[1])
print(dic)

运行结果

{1: {0: [5], 3: [0]}, 2: {0: [3], 1: [0]}, 3: {1: [0], 6: [0]}, 4: {1: [0], 5: [0]}, 5: {8: [0]}}

完全符合预期结果。

内容的提问来源于stack exchange,提问作者user21054862

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:16:13