"Frank Millman" <fr...@chagford.com> writes: > Let's see if I can explain. I am using 't' and 'r' instead of 'tree' > and 'root', but otherwise it is the same as your original example. > >>>> t = {} >>>> r = t >>>> id(t) > 2542235910088 >>>> id(r) > 2542235910088 > > At this point, t and r are both references to the same empty dictionary. > >>>> r = r.setdefault('a', {}) > > This has done two things. > > It has inserted the key 'a' into the dictionary, and set its value to {}. > >>>> t > {'a': {}} >>>> id(t) > 2542235910088 > > It has also rebound 'r' so that it now references the new empty > dictionary that has been inserted.
I guess this is where I fell of the wagon previously. I got it now. >>>> r > {} >>>> id(r) > 2542234429896 >>>>t['a'] > {} >>>> id(t['a']) > 2542234429896 > > Now continue this process with r = r.setdefault('b', {}), and watch > what happens. OK, so what happens is that now t references the dictionary with {'a': {}} and r references the empty dict inside that. So when we assign to r again, it's the empty dict inside t (the one accessed by key 'a') that changes to {'b': {}} and t becomes {'a': {'b': {}}}. -- https://mail.python.org/mailman/listinfo/python-list