0

I'm having trouble with working with this array containing a dictionary. I made the code as small as I could so the problem could be seen more easily but I'm working with a bigger array, of course.

I just want to operate with a two copies of the array and change their values to my needs, each of which can be different for the different copy of the array. So, I operate with one of the copy but I just don't understand why I'm getting the operation replicated in the other copy of the array too.

The code:

#set of data
value_indicador = [{'value': 98.0}]
value_indicador_positivo = value_indicador
value_indicador_negativo = value_indicador

for x in range(0, len(value_indicador_negativo)):

    value_indicador_negativo[x]['value'] = value_indicador_negativo[x]['value']*0.95

#what I'd like to get
value_indicador = [{'value': 98.0}]
value_indicador_positivo = [{'value': 98.0}]
value_indicador_negativo = [{'value': 93.1}]

#what I'm actually getting
value_indicador = [{'value': 93.1}]
value_indicador_positivo = [{'value': 93.1}]
value_indicador_negativo = [{'value': 93.1}]
Didina Deen
  • 195
  • 2
  • 17

1 Answers1

2

You didn't create a copy of the dict, just another reference to the same one. To truly copy it you can simply do this:

dict_a = {'value': 98.0}
dict_b = dict_a.copy()

And for a list:

list_a = ['value', 98.0]
list_b = list_a[:]  # This is called slicing, you simply take all the content from the other list

So your example would need to be like this:

value_indicador = [{'value': 98.0}]
value_indicador_positivo = value_indicador
value_indicador_negativo = [d.copy() for d in value_indicador]
Matthias Schreiber
  • 2,347
  • 1
  • 13
  • 20