Why does the following code show None
for b, and not {'a': 1, 'e': 2}? 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
. This is why
b = d.copy().update({'e':2})
sets b
to equal None
, while
d.update({'c':3})
modifies d
.
A lot of Python methods behave this way. For example, list.sort
and random.shuffle
also modify an object and return 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.