Python - How to copy a ImmutableDict to a mutable dict?

Viewed 283

I'm trying to do a hard copy on a dictionary to avoid modifying the values of original one.

Here is my code:

import copy
d1 = {1: 1}
d2 = copy.deepcopy(d1)
d2[1] = None

What if d1 is a ImmutableDict? How can I copy one and allow it to be modified?

import immutabledict
d1 = immutabledict.immutabledict({1: 1})
d2 = copy.deepcopy(d1)
d2[1] = None  # TypeError: 'immutabledict' object does not support item assignment
2 Answers

Calling dict will create the copy and allow you to mutate d2

import immutabledict
d1 = immutabledict.immutabledict({1: 1})
d2 = dict(d1)
d2[1] = None

This correctly updates d2 and does not change d1.

If you really need to copy use d2 = {**d1}

Related