修改字典的副本而不更改原始字典

时间:2018-04-22 06:57:07

标签: python python-3.x 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}}

和我一起工作的另一个词:

{'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'}}

最终,我试图做的操作:

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']

执行后,我最终输出:

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}}

database['asteroids]['5 10']['capacity]的值仍应为12.(或者无论如何,这是我希望的......)

我将不胜感激任何帮助!

谢谢

0 个答案:

没有答案