0

I'm not sure if I am going crazy here. I have numerical data stored in a dictionary which I will run a function to alter that data. Before I do this, I want to temporarily store the data to compare with the next iteration. In this example, dictionary is the dictionary in question and update_data is a function which manipulates the values of the object 'data' in the dictionary.

example:

for i in range(n_iterations):
       old_data           = dictionary.get('data')
       #call function which manipulates data
       dictionary['data'] = update_data(dictionary) 
       diff = max(dictionary['data']-old_data)

when I compare the old and new, they are the same through each iteration. diff is always 0 and when I compare them visually, it seems that when I set old_data, I am implying a global link between the variable old_data and the dictionary value.

Can someone please clarify the linkages between the dictionary object and the variable in the above example? Also, can someone suggest a workaround to storing the object before it is manipulated? Thank you

handroski
  • 81
  • 2
  • 3
  • 15
  • Can you provide a [mcve]? Honestly, I don't follow you here... What, *exactly* is `dictionary.get('data')` returning, you say it is "numerical" data, but is it actually some kind of container which you mutate in `update_data`? – juanpa.arrivillaga Oct 17 '17 at 23:43
  • 2
    depends what `update_data` actually does. I'm guessing it modifies the object in the dictionary, rather than creating a new object and replacing the value in the dictionary. In which case, since `old_data` is just a reference to the same object, yes, they are "linked". – Blorgbeard Oct 17 '17 at 23:43
  • Yep, this is it. Is there a way to simply define a variable as the object in its current state? – handroski Oct 17 '17 at 23:47
  • 1
    If you're trying to break links, you could try `copy.deepcopy` (or `copy.copy` if you don't need deep copying). – ShadowRanger Oct 17 '17 at 23:49
  • @ShadowRanger I believe this is the solution to my problem. – handroski Oct 17 '17 at 23:53
  • @Blorgbeard answered my ambiguous question. Thank you both. – handroski Oct 17 '17 at 23:53

1 Answers1

0

Answered here

In the example, what I intended to do was to make an independent copy of the dictionary. What python did was create a new reference to that dictionary. To preserve independence, as in the comments by @ShadowRanger and in the link above, you need to make an explicit copy of the dictionary and its values. Following the example in the question, this can be achieved with

import copy

old_data = copy.deepcopy(dictionary)['data']

now old_data is an independent 'copy' of the values in dictionary['data'].

handroski
  • 81
  • 2
  • 3
  • 15