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

Python字典键唯一但值被最后条目覆盖问题求助

字典引用导致的内容覆盖问题:原因与修复方案

问题根源

你遇到的问题核心是Python中可变对象的引用特性:
你在类的__init__方法中初始化了self.single_entry作为实例的字典属性,每次循环时只是修改这个同一个字典的内容,然后将它的引用赋值给self.all_entries[i]。由于字典是可变对象,赋值操作传递的是引用而非副本,最终all_entries里的所有键都指向同一个single_entry字典,自然会被最后一次循环的内容完全覆盖。

修复方案

有两种简单的修复方式,根据你的需求选择:

方案1:每次循环创建新字典(推荐)

直接将single_entry的初始化移到循环内部,每次迭代都生成一个全新的字典,避免复用同一个引用:

class CPUcheck():
    def __init__(self, emul):
        self.all_entries = {}
        self.emul = emul

    def populate_threads(self, iter):
        if self.emul == "ABC":
            for i in range(1, iter+1):
                single_entry = {}  # 每次循环创建新的空字典
                cmd = "command > output.txt"
                os.system(cmd)
                with open("output.txt", mode="r") as file:
                    for line in file.readlines():
                        # 解析逻辑
                        single_entry[matchObj.group(1).strip()] = int(matchObj.group(2))
                self.all_entries[i] = single_entry

方案2:存入字典副本(保留类属性场景)

如果需要保留self.single_entry作为类实例属性,在存入all_entries时创建该字典的副本即可:

class CPUcheck():
    def __init__(self, emul):
        self.single_entry = {}
        self.all_entries = {}
        self.emul = emul

    def populate_threads(self, iter):
        if self.emul == "ABC":
            for i in range(1, iter+1):
                self.single_entry.clear()  # 清空原有内容,准备新的解析
                cmd = "command > output.txt"
                os.system(cmd)
                with open("output.txt", mode="r") as file:
                    for line in file.readlines():
                        # 解析逻辑
                        self.single_entry[matchObj.group(1).strip()] = int(matchObj.group(2))
                self.all_entries[i] = self.single_entry.copy()  # 存入字典副本而非引用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 06:10:10