-2

So I try to make a deepcopy of dict and update it with some additional data (I don't want to change my original dict):

>>> a = {1:1}
>>> print(a)
{1: 1}
>>> b = copy.deepcopy(a).update({2:2})
>>> print(b)
None

But when I do it in another way, it works:

>>> a = {1:1}
>>> b = copy.deepcopy(a)
>>> b.update({2:2})
>>> print(b)
{1: 1, 2: 2}

Why Python sets b variable to None when I update on same line?

I've also try to make deepcopy of original dict:

>>> a = {1:1}
>>> a = copy.deepcopy(a).update({2:2})
>>> print(a)
None

But:

>>> a = {1:1}
>>> a = copy.deepcopy(a)
>>> a
{1: 1}

So this is dict.update issue? Or maybe it's CPython related behavior?

valignatev
  • 6,020
  • 8
  • 37
  • 61
  • This is literally in the **first line** of [the documentation](https://docs.python.org/2/library/stdtypes.html#dict.update): *"Return `None`."* I've no idea why you ever thought this was strange. – jonrsharpe Nov 18 '15 at 14:13
  • It seems that I've just overdone this. I was so confused and look for reason on deepcopy side – valignatev Nov 18 '15 at 14:16
  • Your two versions weren't equivalent -`b = copy.deepcopy(a).update({2:2})` becomes `b = copy.deepcopy(a);` **`b =`** `b.update({2:2})`. This was never related to `deepcopy`. – jonrsharpe Nov 18 '15 at 14:17
  • Well, I understand. It's because I didn't know earlier about `mutators return None`. So I thought that `update` behave like `pop`. Now I know though – valignatev Nov 18 '15 at 14:21

1 Answers1

1

dict.update updates your dictionary in place, it does not return it so b is not what you think it is.

Josh J
  • 6,813
  • 3
  • 25
  • 47