How to avoid "pointing to same object" while creating nested dictionary using zip and map?

Question:

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.

Asked By: Trilokinath Modi

||

Answers:

Just don’t do the prototype thing:

return {x: {'uniqueDict': []} for x in aa}

Trying to deep-copy a template object in Python will usually be slow, error-prone, and awkward, compared to creating a new object the same way you would have created the template.

Answered By: user2357112
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.