0

I created a dictionary using fromkeys and by manually filling it. When I want to update the values of one key, I end up updating all the values when I use the dictionary created by fromkeys. Why is this happening?

ex = dict.fromkeys(list(range(3)), set())
print(ex)
ex[1].update([0,1])
print(ex)

ex2 = {0: set(), 1: set(), 2: set()}
print(ex2)
ex2[1].update([0,1])
print(ex2)
    

Results

{0: set(), 1: set(), 2: set()}

{0: {0, 1}, 1: {0, 1}, 2: {0, 1}}

{0: set(), 1: set(), 2: set()}

{0: set(), 1: {0, 1}, 2: set()}
  • Does this answer your question? [dict.fromkeys all point to same list](https://stackoverflow.com/questions/15516413/dict-fromkeys-all-point-to-same-list) – Craig Sep 26 '20 at 21:44
  • You can initialize your dictionary using a comprehension: `ex = {k:{} for k in range(3)}` and then you will have independent sets for each of your keys. – Craig Sep 26 '20 at 21:48
  • Here's another similar question: https://stackoverflow.com/questions/11509721/how-do-i-initialize-a-dictionary-of-empty-lists-in-python – Craig Sep 26 '20 at 21:49

1 Answers1

1

The fromkeys() method returns a dictionary with the specified keys and the specified value.

Syntax-

dict.fromkeys(keys, value)

keys - An iterable specifying the keys of the new dictionary.

value - Optional. The value for all keys.

When value for one key changes, the other values also get modified because each element is assigned a reference to the same object (points to the same object in the memory).

Shradha
  • 2,232
  • 1
  • 14
  • 26