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:

  1. why?

  2. 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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -