[英]Using a loop to .setdefault on Dict Creates Nested Dict
我想知道为什么
tree = {}
def add_to_tree(root, value_string):
"""Given a string of characters `value_string`, create or update a
series of dictionaries where the value at each level is a dictionary of
the characters that have been seen following the current character.
"""
for character in value_string:
root = root.setdefault(character, {})
add_to_tree(tree, 'abc')
创建{'a': {'b': {'c': {}}}}
而
root = {}
root.setdefault('a', {})
root.setdefault('b', {})
root.setdefault('c', {})
创建{'a': {}, 'b': {}, 'c': {}}
是什么让我们在循环的每次迭代中进入指定的dict值?
root.setdefault(character, {})
返回root[character]
如果character
是root
的键,或者返回空dict {}
。 它与root.get(character, {})
相同,只是如果character
不是root
的键,它也会指定root[character] = {}
。
root = root.setdefault(character, {})
重新分配root
到一个新的字典,如果character
是不是已经在原来的一个重要root
。
In [4]: root = dict()
In [5]: newroot = root.setdefault('a', {})
In [6]: root
Out[6]: {'a': {}}
In [7]: newroot
Out[7]: {}
相反,使用root.setdefault('a', {})
而不将其返回值重新分配给root
工作:
tree = {}
def add_to_tree(root, value_string):
"""Given a string of characters `value_string`, create or update a
series of dictionaries where the value at each level is a dictionary of
the characters that have been seen following the current character.
"""
for character in value_string:
root.setdefault(character, {})
add_to_tree(tree, 'abc')
print(tree)
# {'a': {}, 'c': {}, 'b': {}}
对于任何和我一样慢的人。 答案为“为什么(上面)函数产生{'a': {'b': {'c': {}, 'd': {}}}}
而不是{'a': {}, 'b': {}, 'c': {}}
?“ 是:
因为我们在一个函数中循环并且每次都将结果重新分配给root,这有点像在他们一直说的电视广告中,“但是等等! 还有更多!”。 所以当.setdefault在'a'上被调用时,在返回之前,结果是{'a': {}}
被保持在{循环内},而它在'b'上运行,产生{'b': {}}
,在{'a': {}}
,并且保持在侧面并运行{'a': {}}
,然后整个事物从循环返回并应用于树。 请注意,每次,.setdefault实际返回的内容都是默认值,在本例中为{}
。 这是一个Python Visualizer插图的过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.