Dict's are mutable objects in python. When you assign dict
to other variable it's assigned by reference, what leads to problem you have described.
So in your case both values of keys in doc
dict (field1,field2) point to same variable (docsite
). That's way you have such behaviour.
To fix that use dict copy method before assigning it to doc
keys.
docsite = {'text1':1, "text2":1}
doc = {
"field1": docsite.copy(),
"field2": docsite.copy()
}
There are two types of copies in python, deepcopy and shallow copy ( see that SO answer to understand difference between them).
The example above is just shallow copy of docsite
. However you can make deepcopy by using code below:
import copy
docsite = {'text1':1, "text2":1}
doc = {
"field1": copy.deepcopy(docsite),
"field2": copy.deepcopy(docsite)
}
See Immutable vs Mutable types that's good SO question to discover that topic for python...