0

I have a list with certain value. I need to assign the data in the list as initial values to all keys in a dictionary. I want that only data of the variable should be assigned to the key and not the variable. The code I have return changes the variable value thereby changing it for every key. How to copy only data from a variable to assign to a key. I understand that It the code has created a reference of same variable. I want to know how to assign data from the variable without any reference

#Initialize Dictionary with values of List
my_list = [0] * 20
my_dict = {"A_key":my_list ,"B_key":my_list,"C_key":my_list}
#Edit Dictionary
my_dict["A_key"][4] = "Changed_Data"
#Print values
print(my_dict)
print(my_list)

Actual Result

{'B_key': [0, 0, 0, 0, 'Changed_Data', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'A_key': [0, 0, 0, 0, 'Changed_Data', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'C_key': [0, 0, 0, 0, 'Changed_Data', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}

[0, 0, 0, 0, 'Changed_Data', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Expected Result

{'B_key': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'A_key': [0, 0, 0, 0, 'Changed_Data', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'C_key': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Omkar Kekre
  • 327
  • 2
  • 8

1 Answers1

2

The reason this is happening is you're modifying your main list and not the value for that specific key, you could create multiple list as assign them or you could create multiple copies of the list when assigning them to the dictionary. You can do it by the following method,

my_dict = {"A_key":my_list[:] ,"B_key":my_list[:],"C_key":my_list[:]}
my_dict["A_key"][4] = "Changed_Data"

What is happening here is that you are copying the list from the beginning to the end of the list. This is called as list slicing where you "slice" the list from one end to another. When you slice the list it returns back a new list from the start index to the end index.

You provide the start index using, [0:10], where 0 is the start and 10 is the end. If you do not provide the start and the end then the entire list is returned. This can be used for copying the list.

But this is still something called "Shallow Copy" where if you have a list inside this list then the nested list will still be prone to edits to the main list. That can still be resolved using something called as deepcopy using,

from copy import deepcopy
old_list = [1, 2, 3, [4]]
new_list = deepcopy(old_list)
Vinay Bharadhwaj
  • 165
  • 1
  • 17