I would like to avoid pointing to the same object in the below code. Please look at output and desired output stated below.
Code:
import random
prototype = [{'uniqueDict': list()}]
def mapme(somekey):
global aa
aa = [random.randint(0, 5), random.randint(6, 10)]
return dict(zip(aa, len(aa) * prototype))
forSomeKey = ['outer']
FirstSecondOnce = dict(zip(forSomeKey, list(map(mapme, forSomeKey))))
for key in aa:
location = [['first', 'second']]
for ixy in location:
FirstSecondOnce[forSomeKey[0]][key]['uniqueDict'].append(ixy)
print(FirstSecondOnce)
Output:
{'outer': {0: {'uniqueDict': [['first', 'second'], ['first', 'second']]}, 7: {'uniqueDict': [['first', 'second'], ['first', 'second']]}}}
Desired output:
{'outer': {0: {'uniqueDict': [['first', 'second']]}, 7: {'uniqueDict': [['first', 'second']]}}}
Notice that the ['first', 'second']
is appended only once in each key loop iteration, but since they are pointing to same object. I have tried both .copy()
and deepcopy(prototype)
for prototype
, but none has worked. Please suggest how to fix this.
Thank you.