Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python change a value in a dictionary that is a item in a list

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.

like image 619
Firefly Avatar asked Nov 20 '25 05:11

Firefly


2 Answers

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
like image 58
chepner Avatar answered Nov 21 '25 18:11

chepner


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.

like image 41
Holloway Avatar answered Nov 21 '25 19:11

Holloway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!