I am trying to write a Monte Carlo code where I optimize the elements in a dictionary. For example, I define my original dictionary as
A = {}
A[1] = ['a','b','c']
A[2] = ['d','e','f']
This results in
>>> A
{1: ['a', 'b', 'c'], 2: ['d', 'e', 'f']}
Now say that a trial move in my Monte Carlo is to take a random element ‘a’ from A[1] and put it in A[2]. However, I want to keep my original dictionary. So I first create a new dictionary:
B = A
And then in B I make the desired changes
B[1].remove('a')
B[2].append('a')
That results in the modified dictionary that I wanted to obtain:
>>> B
{1: ['b', 'c'], 2: ['d', 'e', 'f', 'a']}
However this has also changed my original dictionary A, which I did want to backup.
>>> A
{1: ['b', 'c'], 2: ['d', 'e', 'f', 'a']}
Is there any way that I can do this?
Thanks for your help!
You need to do a deep copy of the dictionary:
If you don’t do this, the array references are shared between the dictionaries.