function call questions
Peter Otten
__peter__ at web.de
Wed Oct 19 03:16:34 EDT 2016
chenyong20000 at gmail.com wrote:
> 在 2016年10月19日星期三 UTC+8上午11:46:28,MRAB写道:
>> On 2016-10-19 03:15, chenyong20000 at 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.
>> >
>> You call the .setdefault method with a key and a default value.
>>
>> The .setdefault method does this: if the key is in the dict, it returns
>> the associated value, else it puts the key and the default into the dict
>> and then returns the default.
>
> thanks for the reply. I understand this. I'm now confused on why tree got
> its magic result.
Perhaps it is easier to understand if you rewrite the function without
setdefault()?
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
if ch not in root: # always true if the root arg is an empty dict
root[ch] = {}
root = root[ch] # inside the function the inner dict becomes the new
# root
print "root is", root
print "tree is", tree
More information about the Python-list
mailing list