在 2016年10月20日星期四 UTC+8下午1:32:18,Frank Millman写道: > wrote in message > news:5506e4d8-bd1d-4e56-8d1b-f71fa8293...@googlegroups.com... > > 在 2016年10月19日星期三 UTC+8下午3:17:18,Peter Otten写道: > > chenyong20...@gmail.com wrote: > > > > > 在 2016年10月19日星期三 UTC+8上午11:46:28,MRAB写道: > > >> On 2016-10-19 03:15, chenyong20...@gmail.com wrote: > > >> > Thanks Peter and Anssi for your kind help. Now I'm ok with the first > > >> > question. But the second question still confused me. Why "it seems > > >> > that > > >> > after root = root.setdefault(ch,{}) tree['a'] and root are the same > > >> > object" and follows tree['a']['b']? Thanks. > > >> > > > > please forgive my stupid. I still can't follow this. > > 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. > > >>> r > {} > >>> id(r) > 2542234429896 > >>>t['a'] > {} > >>> id(t['a']) > 2542234429896 > > Now continue this process with r = r.setdefault('b', {}), and watch what > happens. > > Hopefully this will help you to understand. Feel free to ask further if not > sure. > > Frank Millman
Hi Frank, thanks very much for your kind help. Your reply is clear. But I'm hindered by those you've not explained. I'm always confused by "r = r.setdefault('a', {})". when the first loop finished, as what you have pointed out, > >>> t > {'a': {}} > >>> r > {} Then next "r = r.setdefault('b', {})" will run again. Here what is "r" in "r.setdefault('b',{})"? According to final result, it should be "t['a']", which I can't understand. I thought the command is r.setdefault, so it should still be last "r", i.e., empty {}. Could you please let me know what I missed? thanks. -- https://mail.python.org/mailman/listinfo/python-list