How do I change the element of only one list in a Python dictionary of lists?

Question:

I’ve made a dictionary in Python that’s composed of 4 lists as values, with a single letter key for each list. When I try to change a value in only one of the lists by referencing dict_name[key][list index], I’m finding that that same index is changing in the lists for every one of the keys in the dictionary.

Here’s an example of the starting dictionary:

my_dict = {'A': [0, 0, 0, 0], 'C': [0, 0, 0, 0], 'G': [0, 0, 0, 0], 'T': [0, 0, 0, 0]}

And then I try to change a single value in one of the lists by iterating with a for-loop:

test_string = 'WXTZ'
k = len(test_string)

for i in range(k):
    if test_string[i] == 'T':
        my_dict['T'][i] += 1

But the output I’m getting doesn’t make sense:

print(my_dict) = {'A': [0, 0, 1, 0], 'C': [0, 0, 1, 0], 'G': [0, 0, 1, 0], 'T': [0, 0, 1, 0]}

I would think that this should return the following instead:

print(my_dict) = {'A': [0, 0, 0, 0], 'C': [0, 0, 0, 0], 'G': [0, 0, 0, 0], 'T': [0, 0, 1, 0]}

Has anyone else experienced something like this before? How would I change only the ‘T’ list in this case with such a loop, if not this way?

I’m in Python 3 with Atom on Windows 10 if that’s worth knowing. Thanks!

EDIT: A few of you asked about the code that I used to create my_dict. Including that below for reference:

holder = []
my_dict = {}
k = len(string)
for i in range(k):
    holder.append(0)

for char in 'ACGT':
    my_dict[char] = holder
Asked By: charlie maxwell

||

Answers:

Probably is what mark sugested in the comment, you are using the same list object in all the values of the dict.

I tried exactly what you exemplified:

my_dict = {'A': [0, 0, 0, 0], 'C': [0, 0, 0, 0], 'G': [0, 0, 0, 0], 'T': [0, 0, 0, 0]}

my_dict['T'][0] = 1

And that changed to:

{'A': [0, 0, 0, 0], 'C': [0, 0, 0, 0], 'G': [0, 0, 0, 0], 'T': [1, 0, 0, 0]}

Try initializing the dict as that:

my_dict = {'A': [0, 0, 0, 0], 'C': [0, 0, 0, 0], 'G': [0, 0, 0, 0], 'T': [0, 0, 0, 0]}

Or using different list objects like:

list1=[0,0,0,0]

list2=[0,0,0,0]

dict={'A': list1, 'B':list2}

Answered By: Rodrigo Mosken
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.