2

Solution: test_dict = copy.deepcopy(DICT) Thank you, my fellow gamers. May ease of debugging grace you in the future.

I create a copy of a dictionary, I append change to new variable. Change appears in old variable instead.

CHARACTERS = ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A']
DICT = {'key1': "foo", 'key2': "bar", 'key3': CHARACTERS}

def test(self):
    test_dict = DICT.copy()  # first reference of 'test_dict'
    print("DICT before", DICT)
    test_dict['sequence'] += ['G']
    print("DICT after ", DICT)

Output:

DICT before {'key1': "foo", 'key2': "bar", 'key3': ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A']}
DICT after  {'key1': "foo", 'key2': "bar", 'key3': ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A', 'G']}

The letter 'G' is appended to both DICT and test_dict.

Totally spoopy, if you ask me.

Update: I've tried the suggested: test_dict = DICT.copy() but with no luck. What am I doing wrong in the above updated code that includes this?

1 Answers1

0

You don't create a copy, you create a reference. Both variables point to the same are of memory. If you want to create exact copy that does not change the "original", you should use test_dict = DICT.copy(). This creates a shallow copy (doesn't copy nested dicts/lists). To resolve this, a deep copy is needed. One way to get is to use copy.deepcopy function from copy module

import copy

CHARACTERS = ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A']
DICT = {'key1': "foo", 'key2': "bar", 'key3': CHARACTERS}

def test():
    test_dict = copy.deepcopy(DICT) # first reference of 'test_dict'
    print("DICT before", DICT)
    test_dict['key3'] += ['G']
    print("DICT after ", DICT)

test()

This outputs as expected:

DICT before {'key1': 'foo', 'key2': 'bar', 'key3': ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A']}
DICT after  {'key1': 'foo', 'key2': 'bar', 'key3': ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A']}
Galunid
  • 578
  • 6
  • 14
  • 1
    I knew it was something to do with pointers! I have a background in ASM and C++, but as Python is high-level, it deals with these concepts all for us. –  Feb 22 '21 at 20:19
  • 1
    However, I just tried 'test_dict = DICT.copy()' but to no luck ;( –  Feb 22 '21 at 20:20
  • 1
    My bad, I'll edit the answer in a second, you need to create deep copy (copy the nested stuff too) – Galunid Feb 22 '21 at 20:25
  • 1
    Please check out the edited answer, hopefully this resolves your problem – Galunid Feb 22 '21 at 20:28