Skip to content
Advertisement

How to use a dictionary to modify an array in python

I am trying to use a dictionary (created by reading the content of a first file) to modify the content of an array(created by reading the content of a second file) in order to return as many modified arrays as their are keys in the dictionary with the modification corresponding the position and change in the original array indicated in the values for each key.

From a minimal example, if my dictionary and my list are:

change={'change 1': [(1, 'B'), (3, 'B'), (5, 'B'), (7, 'B')], 'change 2': [(2, 'B'), (4, 'B'), (6, 'B')]}
s=['A', 'A', 'A', 'A', 'A', 'A', 'A']

Then, I would like my code to return two lists:

['B', 'A', 'B', 'A', 'B', 'A', 'B']
['A', 'B', 'A', 'B', 'A', 'B', 'A']

I tried to code this in python3:

change={'change 1': [(1, 'B'), (3, 'B'), (5, 'B'), (7, 'B')], 'change 2': [(2, 'B'), (4, 'B'), (6, 'B')]}
s=['A', 'A', 'A', 'A', 'A', 'A', 'A']
for key in change:
    s1=s
    for n in change[key]:
        s1[n[0]-1] = n[1]
    print(key, s1)
    print(s)

However it seems that even if I am only modifying the list s1 which is a copy of s, I am nontheless modifying s as well, as it returns:

change 1 ['B', 'A', 'B', 'A', 'B', 'A', 'B']
['B', 'A', 'B', 'A', 'B', 'A', 'B']
change 2 ['B', 'B', 'B', 'B', 'B', 'B', 'B']
['B', 'B', 'B', 'B', 'B', 'B', 'B']

So although I get the first list right, the second isn’t and I don’t understand why.

Could you help me see what is wrong in my code, and how to make it work? Many thanks!

Advertisement

Answer

In your code s1 isn’t a copy of s, it’s just another name for s.

I’d suggest doing this by just building a new list in a comprehension, e.g.:

>>> change={'change 1': [(1, 'B'), (3, 'B'), (5, 'B'), (7, 'B')], 'change 2': [(2, 'B'), (4, 'B'), (6, 'B')]}
>>> s=['A', 'A', 'A', 'A', 'A', 'A', 'A']
>>> for t in change.values():
...     d = dict(t)
...     print([d.get(i, x) for i, x in enumerate(s, 1)])
...
['B', 'A', 'B', 'A', 'B', 'A', 'B']
['A', 'B', 'A', 'B', 'A', 'B', 'A']

But if you change your original code to initialize s1 to s.copy() it seems to work:

>>> for key in change:
...     s1 = s.copy()
...     for n in change[key]:
...         s1[n[0]-1] = n[1]
...     print(s1)
...
['B', 'A', 'B', 'A', 'B', 'A', 'B']
['A', 'B', 'A', 'B', 'A', 'B', 'A']
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement