[英]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.