I would expand the version of Aaron Digulla. Now it is replicated here:
class DictRef(object): def __init__(self, d, key): self.d, self.key = d, key d = {} d.update({ 'key1': ['val1','val2'], 'key2': DictRef(d, 'key1') })
I assume that he wants to replicate the true reference semantics, so accessing 'key2' will always give you the opportunity to get the value of 'key1' as the value. the problem is that d['key1'] is a list , d['key2'] is a DictRef . So, to get the βvalueβ of 'key1' , all you have to do is d['key1'] , but for 'key2' you have to do d[d['key2'].key] . In addition, you cannot link to a link that works enough, it will become d[d[d['key2'].key].key] . And how do you distinguish between a link and a regular value? Probably through type checking with isinstance (v, DictReference) ( ew ).
So, I have a suggestion to fix all this.
Personally, I donβt understand why real link semantics are needed. If they seem necessary, they can be made unnecessary by restructuring the problem or solving the problem. Perhaps even they were never needed, and a simple d.update(key2=d['key1']) would solve the problem.
In any case, to the proposal:
class DictRef(object): def __init__(self, d, key): self.d = d self.key = key def value(self): return self.d[self.key].value() class DictVal(object): def __init__(self, value): self._value = value def value(self): return self._value d = {} d.update( key1=DictVal(['val1', 'val2']), key2=DictRef(d, 'key1') )
Now, to get the value of any key, whether it is a link or not, just do d[k].value() . If there are links to links, they will be dereferenced in the chain correctly. If they form a really long or infinite chain, Python will fail with a RuntimeError for excessive recursion.