Python dictionary with value set to list behaves oddly -


i know list object can changed in place, list() should returns me independent list object each time when called. i'm confused output:

l = [1, 2, 3, 4] # list() should  d = dict.fromkeys(l, list()) print(d) # {1: [], 2: [], 3: [], 4: []} d[1].append(1989) print(d) # {1: [1989], 2: [1989], 3: [1989], 4: [1989]} 

the required output should be:

{1: [1989], 2: [], 3: [], 4: []} 

the problem code fromkeys constructor reuses same value each key. list() evaluated once.

you can use either dict-comprehension:

d = {x:list() x in l} 

or, if know using lists in dictionary, use defaultdict factory:

from collections import defaultdict  d = defaultdict(list) d[1].append(1989) d[2].append(2001)  print(d) # {1: [1989], 2: [2001]} 

Comments