When shallow copying a dictionary in Python, why is modifying a list value reflected in the original but a string value is not?

huangapple go评论62阅读模式
英文:

When shallow copying a dictionary in Python, why is modifying a list value reflected in the original but a string value is not?

问题

使用.copy()会创建一个字典的浅拷贝,所以当你修改拷贝时,它会反映在原始字典中(因为它是一个引用)。当字典的值是列表时,的确是这样。然而,当值是字符串时,更改不会反映在原始字典中。示例:

In [36]: x = {"string": "example", "list": []}

In [37]: y = x.copy()

In [38]: x
Out[38]: {'string': 'example', 'list': []}

In [39]: y
Out[39]: {'string': 'example', 'list': []}

In [40]: y["string"] += " one"

In [41]: x
Out[41]: {'string': 'example', 'list': []}

In [42]: y
Out[42]: {'string': 'example one', 'list': []}

In [43]: y["list"].append("one")

In [44]: x
Out[44]: {'string': 'example', 'list': ['one']}

In [45]: y
Out[45]: {'string': 'example one', 'list': ['one']}

为什么这种行为会根据键的值而改变呢?我知道应该在拷贝后使用copy.deepcopy进行修改,但是我对这种行为感到非常困惑。

英文:

My understanding is that using .copy() creates a shallow copy of a dictionary, so when you modify the copy, it will be reflected in the original (since it is a reference). When the dictionary value is a list, this is indeed the case. However, when the value is a string, the change is not reflected in the original. Example:

In [36]: x = {"string": "example", "list": []}

In [37]: y = x.copy()

In [38]: x
Out[38]: {'string': 'example', 'list': []}

In [39]: y
Out[39]: {'string': 'example', 'list': []}

In [40]: y["string"] += " one"

In [41]: x
Out[41]: {'string': 'example', 'list': []}

In [42]: y
Out[42]: {'string': 'example one', 'list': []}

In [43]: y["list"].append("one")

In [44]: x
Out[44]: {'string': 'example', 'list': ['one']}

In [45]: y
Out[45]: {'string': 'example one', 'list': ['one']}

Why does this behavior change based on the value of the key? I'm aware that copy.deepcopy should be used for modification after copying, but I'm very confused by this behavior.

答案1

得分: 1

行为不会根据字典中的值而改变。您正在执行两种完全不同的操作,因此您看到的结果是不同的。

list的情况下,您正在修改列表。在str的情况下,您没有修改字符串。如果您对列表执行相同的操作:

y["list"] = y["list"] + ["one"]

您会看到相同的行为。

英文:

The behavior doesn't change on based on the value in the dict. You are doing two completely different things so the result you are seeing is different.

In the list case, you are mutating the list. In the str case, you are not mutating the string. If you did the same thing with the list:

y["list"] = y["list"] + ["one"]

You would see the same behavior.

huangapple
  • 本文由 发表于 2023年7月13日 22:26:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76680510.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定