结合两个字典,并且仍然具有对 Python 中原始对象的引用



我有两个字典,我想合并两者的内容,以便以组合的方式处理它们。我做以下事情

a = {'one': 'fileone', 'two': 'filetow'}
b = {'three': 'filethree', 'four': 'filefour'}
clist = a.values() + b.values()
If I change anything in the clist, the change is not reflected in list a or b.

我理解的一件事是字符串是不可变的类型。

我仍然希望能够引用旧字符串,并且对它们的更改必须反映在原始字符串中。

谢谢

如果你用可变的东西包装你的字符串(确实是不可变的(,你可以得到我认为你正在寻找的效果

a = {'one': ['fileone'], 'two': ['filetwo']}
b = {'three': ['filethree'], 'four': ['filefour']}
clist = a.values() + b.values()
print(clist)
a['one'][0] = 'different_file'
print(clist)

输出如下所示:

[['filetwo'], ['fileone'], ['filefour'], ['filethree']]
[['filetwo'], ['different_file'], ['filefour'], ['filethree']]

正如您已经指出的,字符串是不可变的。 你的clist是一个 Python list ,这意味着它是一个可变的字符串集合,通过引用保存。 您可以添加到列表中或从列表中删除,但显然这对ab没有影响。 您也可以替换列表中的字符串,但这同样对ab没有影响。 不能"修改"列表中的字符串,因为字符串是不可变的。

所以,你把自己画进了一个角落。 您需要重新考虑代码的某些部分。 例如,你可以创建一个保存字符串的小类,然后如果你存储该类的实例而不是实际的字符串,你将能够通过交换对里面字符串的引用来"修改"它们。 额外的间接层。

您可以使用另一个字典的值更新其中一个字典。

a.update(b)

但是,a的进一步变化仍然不会反映在b中。为此,我想您最好创建自己的数据结构。

# Something on these lines
class MyDict(dict):
    def __init__(self, dict1, dict2):
        super(MyDict, self).__init__(dict1, dict2)
        self.dict1 = dict1
        self.dict2 = dict2
    def __getitem__(self, key):
        if key in self.dict1:
            return self.dict1[key]
        if key in self.dict2:
            return self.dict2[key]
        return super(MyDict, self).__getitem__(key)
    def __setitem__(self, key, value):
        if key in self.dict1:
            return self.dict1[key] = value
        elif key in self.dict2:
            return self.dict2[key] = value
        return super(MyDict, self).__setitem__(key, value)

现在,如果你想改变字符串,那是不可能的。字符串在 Python 中是不可变的。

最新更新