Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python problem – Editing value in dictionary inside two dimensional list edits the whole matrix instead of only one item

I have a matrix (two-dimensional list) filled with dictionary-type variable in the entire scope containing "val": False

The problem is when I want to change only one item in the matrix and chanhge the value to True for this one paticular item.

Somehow this part of code: matrix[3][2]["val"] = True causes the entire matrix to update the "val" value and changes all False values to True.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my code:

defval = {
  "val": False
}

matrix = []

for x in range(5):
  row = []
  for i in range(5):
    row.append(defval)
  matrix.append(row)

matrix[3][2]["val"] = True

>Solution :

This behavior arises due to variables in python being passed by reference rather than by value. For example:

some_dict = {'foo': 'bar'}
other_dict = some_dict # actually references the same object as some_dict
other_dict['foo'] = 'buzz' # update applies to the dictionary object being referenced
print(other_dict) # {'foo': 'buzz'}
print(some_dict) # {'foo': 'buzz'}

Therefore all elements in your matrix actually reference the same dictionary object, and when it is updated, the change is reflected in all references. To avoid this, you can use dictionary’s copy method, which returns a shallow copy of a dictionary. So, your code could look something like this:

defval = {
  "val": False
}

matrix = []

for x in range(5):
  row = []
  for i in range(5):
    row.append(defval.copy())
  matrix.append(row)

matrix[3][2]["val"] = True
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading