0

I want to create a dictionary where the keys are string and the values are the lists. Initially, all lists are empty. Then I want to append an int to a specific list using "append()." The result: the int is appended to ALL list in my dictionary.

d = ['a', 'b', 'c']
my_d = dict.fromkeys(d, [])
my_d['a'].append(4)
print(my_d)

{'a': [4], 'b': [4], 'c': [4]}

I want it to be :

{'a': [4], 'b': [], 'c': []} 

since I appended 4 to my_d['a'] only

  • 2
    Your values are the same reference. Do something like `{k: [] for k in d}` – Mad Physicist Aug 03 '18 at 17:49
  • Another option is `my_d = {}`, then create new lists when you need them with `my_d.setdefault('a', []).append(4)`. That will create a fresh empty list each time. Or use `collections.defaultdict(list)`. – PM 2Ring Aug 03 '18 at 18:13
  • 1
    While I completely stand by the dupe hammer, I added an answer to the duplicate question that is a bit more tailored to your needs. See option #3 in particular: https://stackoverflow.com/a/51678197/2988730 – Mad Physicist Aug 03 '18 at 18:26
  • @MadPhysicist I see you aren't a fan of `.setdefault` :) – PM 2Ring Aug 03 '18 at 18:37
  • @PM2Ring. I am, actually. I have never used defaultdict myself in the wild. I'll add something to the answer about that. – Mad Physicist Aug 03 '18 at 18:41
  • @PM2Ring. I've added a note. I don't think `setdefault` is ideal in this case. – Mad Physicist Aug 03 '18 at 18:47

0 Answers0