简体   繁体   中英

Update dict of dict value

I have copied B_cells value into A dictionary. I am trying to add new element A_cell but it's impacting B_cells also

props = {'A_cells': {'t4drc_3': ['Path'],
            'tb4drc_1': ['Path']},

 'B_cells': {'t4drc_3': ['Path'],
             'tb4drc_1': ['Path']}
         }



props_dict['A_cells'] = props_dict['B_cell'].copy()


#Need to append data for A cells only
def append_in_dict_by_option(self, option, data):
        """Adding data in dictionary"""
        for key in props_dict[option].keys():
            self.props_dict[option][key].append(data)

So I was expecting output in A_cells only but it's impacting B_cells . Any idea

{'A_cells': {'t4drc_3': ['Path', data],
                'tb4drc_1': ['Path', data]},

That's because dict.copy returns a shallow copy of the dict. This means you get a new dict instance, but the elements in the dict are the same.

props['A_cells'] is props['B_cells'] #returns False
props['A_cells']['tb4drc_1'] is props['B_cells']['tb4drc_1'] #returns True

Therefore, if you append a value to props['A_cells']['tb4drc_1'], the change will be reflected in props['B_cells']['tb4drc_1'] - they contain the same list instance after all.

UPDATE:

To fix this, change

props_dict['A_cells'] = props_dict['B_cells'].copy()

to

from copy import deepcopy
props_dict['A_cells'] = deepcopy(props_dict['B_cells'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM