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

如何让Python字典中foo和bar键引用同一对象?

让Python字典中多个键引用同一个对象的解决方案

问题核心在于你使用了不可变对象(比如字符串)。Python中不可变对象无法被修改,当执行d["foo"] = "world"时,并不是修改原来的"hello"对象,而是将"foo"键重新指向了新的"world"对象,"bar"键依然指向旧的"hello",因此两者值不会同步。

以下是两种可行的解决方案:

方案1:用可变容器封装值

使用列表、字典这类可变对象作为值,修改容器内部的元素而非直接给键赋值,这样两个键始终指向同一个容器对象。

# 初始化共享的可变容器
shared_value = ["hello"]
d = {
    "foo": shared_value,
    "bar": shared_value
}

# 修改容器内的元素,而非重新给键赋值
d["foo"][0] = "world"

print(d["bar"])  # 输出: ['world']

方案2:自定义同步键的字典类

如果需要直接对键赋值就能同步,可以自定义一个字典类,让指定的键组自动同步引用:

class SharedKeyDict(dict):
    def __init__(self, shared_groups=None, **kwargs):
        super().__init__(**kwargs)
        self.shared_groups = shared_groups or []
        # 初始化时同步共享组的引用
        for group in self.shared_groups:
            if len(group) < 2:
                continue
            base_val = self[group[0]]
            for key in group[1:]:
                self[key] = base_val

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        # 同步共享组内的其他键
        for group in self.shared_groups:
            if key in group:
                for other_key in group:
                    if other_key != key:
                        super().__setitem__(other_key, value)
                break

# 使用示例
d = SharedKeyDict(shared_groups=[("foo", "bar")], foo="hello")
d["foo"] = "world"

print(d["bar"])  # 输出: world

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:02:10