Firefly
Firefly

Reputation: 99

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.

Upvotes: 3

Views: 128

Answers (4)

Firefly
Firefly

Reputation: 99

Thanks all for speedy response All answers worked !!!!! I had not figured that goods1 was not an independent copy.

Upvotes: 0

wa11a
wa11a

Reputation: 181

The best way to do it is to use a package named copy. If you'll have instances in this dictionary the only thing that will help you is copy.deepcopy method. See here https://docs.python.org/2/library/copy.html

Upvotes: 1

Holloway
Holloway

Reputation: 7367

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.

Upvotes: 2

chepner
chepner

Reputation: 530960

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

Upvotes: 3

Related Questions