Python, dictionary copy and update doesn't work?
copy, dictionary, python
Solution
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.
Problem
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} ```