Reputation: 539
Could someone explain me why the output of this code is same value using a dictionary? I thought if I add a key to the corresponding variable dictionary I can manipulate it's values.
Thanks for the help.
>>> sample = {}
>>> listDict1 = {}
>>> listDict1['a'] = 'b'
>>> listDict1['c'] = 'd'
>>> sample["item1"] = listDict1
>>> listDict1['a'] = 'x'
>>> listDict1['c'] = 'y'
>>> sample["item2"] = listDict1
>>> sample
{'item2': {'a': 'x', 'c': 'y'}, 'item1': {'a': 'x', 'c': 'y'}}
I expected:
{'item2': {'a': 'x', 'c': 'y'}, 'item1': {'a': 'b', 'c': 'd'}}
Upvotes: 0
Views: 74
Reputation: 539
using the above suggestion comments, i edit the code and works perfectly fine. Thanks.
sample = {}
listDict1 = {}
listDict1['a'] = 'b'
listDict1['c'] = 'd'
sample["item1"] = dict(listDict1)
listDict1['a'] = 'x'
listDict1['c'] = 'y'
sample["item2"] = dict(listDict1)
print id(sample["item1"])
print id(sample["item2"] )
print sample
OUTPUT:
40012512
40012656
{'item2': {'a': 'x', 'c': 'y'}, 'item1': {'a': 'b', 'c': 'd'}}
Upvotes: 1