In Python programming, dictionaries are a powerful data structure that allows us to associate key-value pairs and efficiently find and manipulate this data. When storing custom objects in a dictionary, we encounter a crucial concept: object assignment in Python is actually reference assignment, not a deep copy of the object itself. This means that when a custom object is placed into a dictionary, the dictionary stores a reference to that object, rather than a brand new copy.
Storing Custom Objects - Basic Example
Suppose we have a simple ____ class:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 创建一个 Person 对象
p1 = Person("Alice", 30)
# 将对象存储到字典中
people_dict = {}
people_dict["alice"] = p1
In this example, the attributes of INLINE_CODE_0 字典现在包含一个键为 INLINE_CODE_1 的项,其值是对 INLINE_CODE_2 类型的 p1
对象的引用。如果我们修改 p1
:
p1.age = 31
When accessing this object through the dictionary, we find that its age has also been updated
print(people_dict["alice"].age) # 输出:31
This is because the dictionary stores references to the same memory address, not independent copies of the objects
The difference between deep copy and shallow copy
This referencing behavior can lead to unexpected results when dealing with nested data structures or custom objects. For example, modifying an object directly stored in a dictionary—especially if it contains mutable attributes like lists or other custom objects—will affect the object retrieved through the dictionary.
class Address:
def __init__(self, street, city):
self.street = street
self.city = city
class Person:
def __init__(self, name, age, address):
self.name = name
self.age = age
self.address = address
address = Address("Main St.", "Springfield")
p1 = Person("Bob", 40, address)
people_dict["bob"] = p1
# 修改原始地址对象
address.city = "Shelbyville"
# 字典中的人的地址也变了
print(people_dict["bob"].address.city) # 输出:Shelbyville
Please provide the Chinese text you want me to translate. I am ready when you are!
To avoid problems caused by this shared state, sometimes we need to ensure that the dictionary stores a complete copy of an object, rather than a reference. Python provides the copy()
function to achieve this goal:
import copy
# 使用深拷贝存储对象
people_dict["bob_deepcopy"] = copy.deepcopy(p1)
# 此时即使修改原始地址对象,深拷贝的对象不会受影响
address.city = "Capital City"
print(people_dict["bob"].address.city) # 输出:Capital City
print(people_dict["bob_deepcopy"].address.city) # 输出:Shelbyville
When using dictionaries to store custom objects in Python, be mindful that object references are stored by default. For situations requiring independent state, use deep copying to avoid unexpected data changes due to shared references.