0

I'm trying to modify the copy of a dictionary, and only the copy, in a loop but it still modifies the original as well.

I don't encounter this problem when working without loop...

Here's my original dictionary :

database['asteroids] = {'20 6': {'capacity': 12, 'pos': [20, 6], 'farm_rate': 2}, '5 21': {'capacity': 12, 'pos': [5, 21], 'farm_rate': 2}, '10 14': {'capacity': 12, 'pos': [10, 14], 'farm_rate': 1}}

And the other dictionay I'm working with :

{'shipOne': {'area': [[20, 3], [21, 3], [19, 3], [20, 4], [20, 2]],'attack': 0,'cost': 2,'life': 3,'portée': 0,'position': [20, 3],'remaining_tonnage': 4,'status': 'unlock','taille': 5,'tonnage': 4,'type': 'excavator-M'},'shipTwo': {'area': [[20, 3], [21, 3], [19, 3], [20, 4], [20, 2]],'attack': 0,'cost': 2,'life': 3,'portée': 0,'position': [20, 3],'remaining_tonnage': 4,'status': 'unlock','taille': 5,'tonnage': 4,'type': 'excavator-M'}}

And eventually, the operation I'm trying to do :

ships_dest = dict()
samp_asteroids = dict(database['asteroids'])

for ship in database['player1']['ships']:
    ships_dest.update({ship:''})
    taxicab = dict()

    for asteroid in samp_asteroids:

        if ships_dest[ship] == '':

            if database['asteroids'][asteroid]['capacity'] != 0:

                ships_dest.update({ship:database['asteroids'][asteroid]['pos']})

                samp_asteroids[asteroid]['capacity'] -= database['player1']['ships'][ship]['tonnage']

After execution, I end up with this output :

ships_dest = {'shipTwo': [5, 21], 'shipOne': [5, 21]}

database['asteroids'] = {'5 21': {'pos': [5, 21], 'capacity': 4, 'farm_rate': 2}, '20 6': {'pos': [20, 6], 'capacity': 12, 'farm_rate': 2}, '10 14': {'pos': [10, 14], 'capacity': 12, 'farm_rate': 1}}

samp_asteroids = {'5 21': {'pos': [5, 21], 'capacity': 4, 'farm_rate': 2}, '20 6': {'pos': [20, 6], 'capacity': 12, 'farm_rate': 2}, '10 14': {'pos': [10, 14], 'capacity': 12, 'farm_rate': 1}}

The value of database['asteroids]['5 10']['capacity] should still be 12. (or in any case, this is what I hoped for...)

I would be grateful for any help !

Thank you

jpp
  • 159,742
  • 34
  • 281
  • 339
Manoa
  • 37
  • 6

0 Answers0