0

I want to add 17 at the position 2 in my dictionary. When I run this code, 17 is everywhere.

dic = dict.fromkeys(range(4), [])

print("dic begin : ", dic)

dic[1].append(17)

print("dic end : ", dic)

I get this output :

('dic begin : ', {0: [], 1: [], 2: [], 3: []}) ('dic end : ', {0: [17], 1: [17], 2: [17], 3: [17]})

What am I doing wrong ?

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Choca
  • 13
  • 3
  • 1
    Possible duplicate of ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – snakecharmerb Nov 02 '19 at 14:36
  • By passing the list constructor to dict.fromkeys you are giving each key _the same list_ as its value. You might prefer to use [collections.defaultdict(list)](https://docs.python.org/3/library/collections.html#collections.defaultdict) – snakecharmerb Nov 02 '19 at 14:38
  • Does this answer your question? [dict.fromkeys all point to same list](https://stackoverflow.com/questions/15516413/dict-fromkeys-all-point-to-same-list) – snakecharmerb Sep 08 '20 at 07:32

1 Answers1

1

So when you use the dict.fromkeys(keys, value) method, only the reference of the value is passed! so when you mutate one all of those guys get mutated. You can use this -

dic = {i:[] for i in range(4) }
print("dic begin : ", dic)

dic[1].append(17)
print("dic end : ", dic)

Out-

dic begin :  {0: [], 1: [], 2: [], 3: []}
dic end :  {0: [], 1: [17], 2: [], 3: []}
pka32
  • 5,176
  • 1
  • 17
  • 21