我有以下代码:
some = {}
stat = {'matches_played': 0, 'won': 0, 'draws': 0, 'loss': 0, 'points': 0}
some = {'Arsenal': stat}
some.update({'Chelsea': stat})
some['Arsenal']['won'] += 1
some['Chelsea']['loss'] += 1
print(some)
结果是:
{'Arsenal': {'matches_played': 0, 'won': 1, 'draws': 0, 'loss': 1, 'points': 0},
'Chelsea': {'matches_played': 0, 'won': 1, 'draws': 0, 'loss': 1, 'points': 0}}
但是,我需要
{'Arsenal': {'matches_played': 0, 'won': 1, 'draws': 0, 'loss': 0, 'points': 0},
'Chelsea': {'matches_played': 0, 'won': 0, 'draws': 0, 'loss': 1, 'points': 0}}
您能解释一下为什么会这样吗?
答案 0 :(得分:4)
stat
同时传递给键“切尔西”和“阿森纳”,以作为参考。您需要创建一个副本。
some = {}
stat = {'matches_played': 0, 'won': 0, 'draws': 0, 'loss': 0, 'points': 0}
some = {'Arsenal': stat}
some.update({'Chelsea': stat.copy()}) # <---- fix it here
some['Arsenal']['won'] += 1
some['Chelsea']['loss'] += 1
print(some)
答案 1 :(得分:0)
尝试复制字典,以避免使用相同的参考文献更新字典
import copy
some = {}
stat = {'matches_played': 0, 'won': 0, 'draws': 0, 'loss': 0, 'points': 0}
some = {'Arsenal': copy.deepcopy(stat), 'Chelsea' : copy.deepcopy(stat)}
some['Arsenal']['won'] += 1
some['Chelsea']['loss'] += 1
print(some)
Results: {'Chelsea': {'loss': 1, 'won': 0, 'draws': 0, 'matches_played': 0, 'points': 0}, 'Arsenal': {'loss': 0, 'won': 1, 'draws': 0, 'matches_played': 0, 'points': 0}}