0

I have the following code:

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)

Result is:

{'Arsenal': {'matches_played': 0, 'won': 1, 'draws': 0, 'loss': 1, 'points': 0}, 
'Chelsea': {'matches_played': 0, 'won': 1, 'draws': 0, 'loss': 1, 'points': 0}}

But, I need

{'Arsenal': {'matches_played': 0, 'won': 1, 'draws': 0, 'loss': 0, 'points': 0}, 
'Chelsea': {'matches_played': 0, 'won': 0, 'draws': 0, 'loss': 1, 'points': 0}}

Can you please explain, why this is happening?

Matthias
  • 12,873
  • 6
  • 42
  • 48
Nava
  • 23
  • 5

2 Answers2

5

stat is passed to both the key "Chelsea" and "Arsenal" as a reference. You need to create a copy of it.

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)
Elise Le
  • 95
  • 7
  • 2
    Nice answer though 1 minor detail. If the dictionary you are copying has nested mutable objects such as a `list` or another `dict` you should use `from copy import deepcopy` and `deepcopy(my_dict)` instead of the built-in copy function. (Such as the other answer). For the provided question this doesn't matter but for future readers it may be relevant. For the given question I would probably use your answer instead of using deepcopy. – Error - Syntactical Remorse Nov 05 '19 at 13:45
  • Thank you, You're a lifesaver) – Nava Nov 05 '19 at 14:32
0

Try to copy the dict to avoid of updating dict with same Reference

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}}
Narendra Lucky
  • 340
  • 2
  • 13