0

I have created a list such as :

abc=[1,2,3,4,5,6]

Now I am creating two empty dictionaries where the key is a no. and value is an empty list.

aa=[i for i in range(0,30,6)]
diction=dict.fromkeys(aa,[])

Another dictionary is :

dict_test={i:[] for i in range(0,30,6)}

The two dictionaries are :

diction is {0:[],6:[],12:[],18:[],24:[]}
dict_test is {0:[],6:[],12:[],18:[],24:[]}

Here, dict_test==diction gives True

Now I just wish to append the values to one key only, therefore,I using a simple for loop :

for i in abc:
    diction[0].append([i])
    dict_test[0].append([i])

But weird behaviour is :

diction becomes :

{0: [[1], [2], [3], [4], [5], [6]],
 6: [[1], [2], [3], [4], [5], [6]],
 12: [[1], [2], [3], [4], [5], [6]],
 18: [[1], [2], [3], [4], [5], [6]],
 24: [[1], [2], [3], [4], [5], [6]]}

dict_test becomes :

{0: [[1], [2], [3], [4], [5], [6]], 6: [], 12: [], 18: [], 24: []}

dict_test is giving the correct output but diction is updating all the keys. Please provide insight into this behaviour as it is quite weird.

Shubham_geo
  • 368
  • 1
  • 4
  • 16
  • Or https://stackoverflow.com/questions/11509721/how-do-i-initialize-a-dictionary-of-empty-lists-in-python. The second argument to `from_keys` can be any object. How is the function supposed to know how to spawn independent clones from it? Ergo all values are references to said object. – user2390182 Oct 21 '20 at 07:09
  • Sorry. I cannot make out as both are the dictionaries.On comparison and type it is giving dictionary as the type,but is there any structural difference between the two. Why all the keys it is updating when only explicitly one is being updated. – Shubham_geo Oct 21 '20 at 07:09
  • 1
    In one dictionary, all values are references to the *same* empty list. The other's values are all *different* empty lists. – user2390182 Oct 21 '20 at 07:11
  • Thanks .I am deleting my question. I got reference to the solution. – Shubham_geo Oct 21 '20 at 07:14
  • 1
    No need to delete. Duplicates collect traffic and point to the answers – user2390182 Oct 21 '20 at 07:15
  • Found simple and compact visible answer : dict_test[0] is dict_test[6] gives result False diction[0] is diction[6] gives result True which truly illustrates that dictinary created from keys method refers to the same list. – Shubham_geo Oct 21 '20 at 08:32

0 Answers0