[英]Python, dictionary copy and update doesn't work?
Why does the following code show None
for b, and not {'a': 1, 'e': 2}? 为什么下面的代码为什么对b不显示
None
,而对{'a':1,'e':2}却不显示? Python 2.7.3 Python 2.7.3
>>>> d = {'a' :1 }
>>>> b = d.copy().update({'e':2})
>>>> print b
None
>>>> d.update({'c':3})
>>>> print d
{'a': 1, 'c': 3}
dict.update modifies the dict but returns None
. dict.update修改字典,但返回
None
。 This is why 这就是为什么
b = d.copy().update({'e':2})
sets b
to equal None
, while 将
b
设置为None
,而
d.update({'c':3})
modifies d
. 修改
d
。
A lot of Python methods behave this way. 许多Python方法都采用这种方式。 For example,
list.sort
and random.shuffle
also modify an object and return None
. 例如,
list.sort
和random.shuffle
也会修改对象并返回None
。 I think Python does this to discourage long "Law-of-Demeter-scoffing" chains of references because they do not improve readability and make finding where exceptions are raised harder. 我认为Python这样做是为了阻止长的“ Demeter-scoff-scoffing”引用链,因为它们不能提高可读性,也很难发现异常引发的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.