Copy of dict messes up original

Hi

I have a dict I’m using to substitute in varaiables in a sympy expression. When I need to exstend the dict with an x-value I seem to over write the original dict.

    temp_dict = params_dict
    print('before: ',params_dict)
    temp_dict[x] = mode
    print('after: ',params_dict)

I get this

before:  {a: np.float64(....), b: np.float64(...), c: np.float64(...)}
after:  {a: np.float64(...), b: np.float64(...), c: np.float64(...), x: ...}

What I’m I missing, why is the original dict altered?

temp_dict = params_dict does not make a copy of the dictionary. It creates a second variable which refers to the same dictionary, and either can be use to access (and modify) that dictionary.

Here’s a Stack Overflow post describing the situation and what you can do: python - How to copy a dictionary and only edit the copy - Stack Overflow

1 Like

Ah!

Thanks