Python Dictionary in Dictionary -
>>> docsite = {'text1':1, 'text2':1} >>> doc = { 'field1': docsite, 'field2': docsite } >>> doc['field2']['text1'] += 2
after when print doc variable, get
>>> doc {'field2': {'text2': 1, 'text1': 3}, 'field1': {'text2': 1, 'text1': 3}}
i change value in field2 only. somehow, values in field1 getting updated.
question:
why?
how resolve it?
your docsite
variable reference dictionnary, therefore, storing @ different locations (e.g. associated different keys in dictionary) make them share same dictionary in memory.
to resolve this, may want copy
of dictionary:
doc = {'field1': docsite, 'field2': docsite.copy()}
note that, if in docsite
have references other objects (list
, other dict
, etc) may have use deepcopy
:
import copy d2 = copy.deepcopy(docsite)
Comments
Post a Comment