val = {
'1': {
'amt': 150.0,
'qty': 10
}
}
ops = {
'add': val,
'remove': val
}
new = {'2': {'amt': 0.0, 'qty': 5}}
ops["add"].update(new)
print(ops)
when you run this, the output is,
{'add': {'1': {'amt': 150.0, 'qty': 10}, '2': {'amt': 0.0, 'qty': 5}}, 'remove': {'1': {'amt': 150.0, 'qty': 10}, '2': {'amt': 0.0, 'qty': 5}}}
So when I update the key 'add' its also updating 'remove' with value 'new'. I am guessing its due to the 'shallow copy' thing. But how to handle this in better way ?
CodePudding user response:
Use deepcopy
to copy nested mutable structures:
from copy import deepcopy
ops = {'add': deepcopy(val),
'remove': deepcopy(val)}
ops['add'].update(new)
Output:
In [3]: ops
Out[3]:
{'add': {'1': {'amt': 150.0, 'qty': 10}, '2': {'amt': 0.0, 'qty': 5}},
'remove': {'1': {'amt': 150.0, 'qty': 10}}}
In [4]: val
Out[4]: {'1': {'amt': 150.0, 'qty': 10}}
CodePudding user response:
Your issue is that val
is the same object for both elements of ops. Try this:
val = {
'1': {
'amt': 150.0,
'qty': 10
}
}
ops = {
'add': val.copy(),
'remove': val.copy()
}
new = {'2': {'amt': 0.0, 'qty': 5}}
ops["add"].update(new)
print(ops)
CodePudding user response:
Ah yes I got it, sorry for mistaken your question. I think you have to copy it and write in the new address (in C/C
what you did was using the same pointer (pointing the same memory address))
you can try this
val = {
'1': {
'amt': 150.0,
'qty': 10
}
}
ops = {
'add': val.copy(),
'remove': val.copy()
}
new = {'2': {'amt': 0.0, 'qty': 5}}
ops["add"].update(new)
by using copy()
you're implicitly write the same dict in different memory address