pythondictionarycopy

Can't directly update a dict deepcopy


I can update a deepcopy of a dictionary in two steps. But when I try to make it a single step it returns None.

from copy import deepcopy

d0 = {'a': 1}
d1 = deepcopy(d0)
d1.update([('b', 2)])
print(d0, d1)

d0 = {'a': 1}
d1 = deepcopy(d0).update([('b', 2)])
print(d0, d1)

Output:

{'a': 1} {'a': 1, 'b': 2}
{'a': 1} None

Why? How to?

Thanks to @tkaus now I know update returns None. This is what I would like to do:

d0 = {'a': 1}
d = {
    'x': deepcopy(d0).update([('b', 2)]),
    'y': deepcopy(d0).update([('b', 3)]),
}

Any ideas?


Solution

  • Why? Because dict.update always operates in place and returns None.

    How? You can invoke an in-place union:

    >>> d0 = {"a": [1]}
    >>> d1 = deepcopy(d0).__ior__([("b", 2)])
    >>> d0["a"].append(3)
    >>> print(d0, d1)
    {'a': [1, 3]} {'a': [1], 'b': 2}
    

    Note that in example cases shown in the original question, a deepcopy isn't required. The values are immutable, so you can safely shallow copy and update in a single operation, which will be simpler and more efficient:

    >>> d0 = {"a": 1}
    >>> d1 = d0 | {"b": 2}  # or: d1 = {**d0, "b": 2}
    >>> print(d0, d1)
    {'a': 1} {'a': 1, 'b': 2}