chenyong20...@gmail.com wrote:

>> > My question is:
>> > (1) why root is always {}?
>> 
>> Because that's what you bind it to in the line
>> 
>> > ...      root = root.setdefault(ch,{})
>> 
>> See <https://docs.python.org/dev/library/stdtypes.html#dict.setdefault>
>> for a description of the the setdefault() method.
> 
> I'm still confused here. root.setdefault(ch,{}) should return {'a':{}},
> right? 

No. Try with something you can recognize (all empty dicts look the same; you 
have to use id() to tell them apart):

>>> d = {1.0: "one"}
>>> d.setdefault(1, "ONE")
'one'
>>> d
{1.0: 'one'}
>>> d.setdefault(2, "TWO")
'TWO'
>>> d
{1.0: 'one', 2: 'TWO'}

setdefault() always returns the value, not the whole dict; if the first 
argument doesn't already exist as a key in the dict the second argument 
becomes the value of the new entry. 

> then this dictionary is referenced by root by "root =
> root.setdefault(ch,{})". why root is an empty dictionary now?
> 
> 
>> 
>> > (2) why tree is {'a': {'b': {'c': {}}}}?
>> 
>> Basically the same answer -- you bind root to the innermost dict and
>> that's where you insert the ch key on the next iteration of the for loop
>> .
>> > (3) why root isn't the same as tree? shouldn't they be the same because
>> > tree is argument passed as root?
>> 
>> You should know the answer by now ;)
> 
> In fact i'm still confused by these answers. Could you please described
> more? thanks


-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to