gro*_*pot 2 python dictionary pointers reference mutability
以下是我认为应该如何工作的:
dictionary = {'k1': {'a': 'b'}, 'k2': [0, 1]}
pointer = dictionary['k1']
print pointer
>>> {'a': 'b'}
pointer.update({'a': 'c'})
print dictionary
>>> {'k1': {'a': 'c'}, 'k2': [0, 1]}
Run Code Online (Sandbox Code Playgroud)
以下内容让我感到沮丧:
pointer = dictionary['k2']
print pointer
>>> [0, 1]
pointer.update([2, 3])
>>> AttributeError: 'list' object has no attribute 'update'
Run Code Online (Sandbox Code Playgroud)
我知道 list 没有更新功能,并且知道我可以执行以下操作:
pointer[0] = 2
Run Code Online (Sandbox Code Playgroud)
...但我想要一个更通用的选项来更新参考值,因此该对象仍然属于字典,但值已更改。
这样做的原因是我有一个嵌套的字典,看起来像:
dictionary['key']['key']['key']['key']
Run Code Online (Sandbox Code Playgroud)
我的问题不是针对列表是否具有更新功能——而是我问的是是否有一种更简洁的方法来引用和更改深度嵌套字典中的值,以便将其存储在参考值中会更好而不是每次我想给它分配一些东西时都把它全部打出来。
谢谢!
编辑:第一个示例中的固定语法
EDIT2:让我说清楚:我知道列表没有update函数,而是询问通用参考值更新
EDIT3:简化问题
小智 5
哪有这回事。引用指向对象,而不是对象内部的位置。时期。这是 Python 对象模型的基本部分。
如果您愿意,可以编写一个表示此类位置的类:
class AttributeReference:
def __init__(self, obj, attr):
self.obj = obj
self.attr = attr
def set(self, value):
setattr(self.obj, self.attr, value)
# add get() and del() and other methods to your heart's content
class ElementReference:
def __init__(self, obj, key):
self.obj = obj
self.key = key
def set(self, value):
self.obj[self.key] = value
# add get() and del() and other methods to your heart's content
Run Code Online (Sandbox Code Playgroud)
然后你可以使用这样的对象而不是 Python 引用。但是使用起来比较笨拙,所以使用门槛比较高。从好的方面来说,嵌套的深度完全无关紧要。如果你想要一个“参考”来dictionary['k1']['k2']['k3']['k4'],这是不行的:ElementReference(dictionary['k1']['k2']['k3'], 'k4')。