[英]Python nested dictionary update in loop
The following code would generate a nested dictionary.以下代码将生成一个嵌套字典。 But
但
l = [1,2,3,4]
n_dict = current = {}
for n in l:
current[n] = {} # would n_dict get update?
# print(current) # just to check
# print(n_dict) # just to check
current = current[n] # would n_dict get update?
# print(current) # just to check
# print(n_dict) # just to check
print(n_dict)
n_dict has become a nested dictionary while current is not. n_dict 已成为嵌套字典,而 current 不是。 So what's the rule that n_dict will or will not get update inside the foo-loop (see the two question lines)?
那么 n_dict 会或不会在 foo-loop 内得到更新的规则是什么(参见两个问题行)?
Thanks谢谢
Let me tell you how the above code is working -让我告诉你上面的代码是如何工作的 -
n_dict = current = {}
When you do this both n_dict and current will point to the same empty dictionary.当你这样做时, n_dict 和 current 都将指向同一个空字典。
Now, in for loop, see this line -现在,在 for 循环中,看到这一行 -
current = current[n]
Here, you're changing the current variable it now points to an empty dict.在这里,您正在更改它现在指向一个空字典的当前变量。 You're using the current variable to modify the original dict and that original dict can be access by n_dict pointer.
您正在使用当前变量来修改原始字典,并且可以通过 n_dict 指针访问原始字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.