0

I have a Python code that looks like this:

import random
import copy

symbols = set('ABC')
values = dict.fromkeys(symbols, [])

for i in range(5):
  value = random.randint(1, 100)
  if value % 3 == 0:
    values['A'].append(copy.deepcopy(value))
  elif value % 3 == 1:
    values['B'].append(copy.deepcopy(value))
  else:
    values['C'].append(copy.deepcopy(value))

print(values)
> {'B': [19, 31, 73, 9, 9], 'A': [19, 31, 73, 9, 9], 'C': [19, 31, 73, 9, 9]}

What I had hope is that each property of the dictionary would have different list of elements, however the end result I get is that all of them have the same numbers (as seen above). Why is this happening although I'm copying the element using deepcopy? How can I solve this issue?

1 Answers1

2

You can use defaultdict to achieve the result you want.

from collections import defaultdict
import random

values = defaultdict(list)

for i in range(5):
  value = random.randint(1, 100)
  if value % 3 == 0:
    values['A'].append(value)
  elif value % 3 == 1:
    values['B'].append(value)
  else:
    values['C'].append(value)

print(values)

And you don't need to copy value

defaultdict(list) creates a new list whenever a key in the dictionary is accessed the first time - so you will have 3 distinct objects as values in the dictionary.

rdas
  • 20,604
  • 6
  • 33
  • 46