Problems with version control for dictionaries inside a python class

Question:

I’m doing something wrong in the code below. I have a method (update_dictonary) that changes a value or values in a dictionary based on what is specificed in a tuple (new_points).

Before I update the dictionary, I want to save that version in a list (history) in order to be able to access previous versions. However, my attempt below updates all dictionaries in history to be like the latest version.

I can’t figure out what I’m doing wrong here.

test_dict = {'var0':{'var1':{'cond1':1,
                            'cond2':2,
                            'cond3':3}
                    }
            }

class version_control:
    
    def __init__ (self, dictionary):
        self.po = dictionary
        self.history = list()
        self.version = 0

    def update_dictionary(self, var0, var1, new_points):
            po_ = self.po
            self.history.append(po_)

            for i in new_points:
                 self.po[var0][var1][i[0]] = i[1]

            self.version += 1
    
    def get_history(self, ver):
        return self.history[ver]


a = version_control(test_dict)

new_points = [('cond1', 2),
             ('cond2', 0)]

a.update_dictionary('var0', 'var1', new_points)

new_points = [('cond3', -99),
             ('cond2', 1)]

a.update_dictionary('var0', 'var1', new_points)

print(a.get_history(0))
print(a.get_history(1))
Asked By: Henri

||

Answers:

Try this

from copy import deepcopy

...
def update_dictionary(self, var0, var1, new_points):
    po_ = deepcopy(self.po)
    self.history.append(po_)

    for i in new_points:
        self.po[var0][var1][i[0]] = i[1]

    self.version += 1
...

The problem here is that when you assign po_= self.po you expect po_ to a variable but actually, you just make a shallow copy of your dictionary. This means if you update the self.po then op_ will automatically update.


To solve this problem using deepcopy from the copy module(Built-in). It will create a new variable.

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