function call questions

Peter Otten __peter__ at web.de
Tue Oct 18 04:15:51 EDT 2016


chenyong20000 at gmail.com wrote:

> Hi,
> I got a function call as this:
> 
>>>>def add_to_tree(root,value_string):
> ...    print "root is %s, value_string is %s" % (root, value_string)
> ...    for ch in value_string:
> ...      print "ch is %s" % ch
> ...      root = root.setdefault(ch,{})
> ...      print "root is", root
> ...      print "tree is", tree
> ...
>>>> tree={}
>>>> txt='abc'
>>>> add_to_tree(tree,txt)
> root is {}, value_string is abc
> ch is a
> root is {}
> tree is {'a': {}}
> ch is b
> root is {}
> tree is {'a': {'b': {}}}
> ch is c
> root is {}
> tree is {'a': {'b': {'c': {}}}}
> 
> 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.

> (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 ;)




More information about the Python-list mailing list