Thanks in advance I want to change a value in a dictionary that is an item in a list
Python 2.6
goods1 = {'coal': 1, 'boxes': 2}
newcastlegoods = goods1
wylamgoods = goods1
goods1 = {}
Newcastle = ['Newcastle' , newcastlegoods]
Wylam = ['Wylam' , wylamgoods]
print Newcastle
print Wylam
Newcastle[1]['coal'] = 4;
print Newcastle
print Wylam
My result is
['Newcastle', {'coal': 1, 'boxes': 2}]
['Wylam', {'coal': 1, 'boxes': 2}]
['Newcastle', {'coal': 4, 'boxes': 2}]
['Wylam', {'coal': 4, 'boxes': 2}]
Note that both coal items have been updated i only want to update newcastle.
Make sure your list contains a copy of the original dictionary, not a reference to it.
goods1 = {'coal': 1, 'boxes': 2}
Newcastle = ['Newcastle' , dict(goods1)]
Wylam = ['Wylam' , dict(goods1)]
print Newcastle
print Wylam
Newcastle[1]['coal'] = 4;
print Newcastle
print Wylam
You are adding the same dictionary to both lists. When you change one, it's the same as changing the other.
In this case you could get around it by using
newcastlegoods = goods1.copy()
wylamgoods = goods1.copy()
Which would create a new dictionary for each.
In this case this is fine. If you put mutable objects in your dictionary, you will need to look at a deep copy or the same objects will be referenced within the new dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With