2
>>> keys = [1, 2, 3]
>>> d = dict(zip(keys, [[]]*len(keys)))
>>> d
{1: [], 2: [], 3: []}
>>> d[1].append(100)
>>> d
{1: [100], 2: [100], 3: [100]}

even copied [] not works:

  • dict(zip(keys, [[][:]]*len(keys)))
  • dict(zip(keys, [copy.deepcopy([])]*len(keys)))

the {1: [100], 2: [], 3: []} is what I wanted exactly.

Keelung
  • 349
  • 5
  • 9
  • The easiest would be one of the solutions [here](https://repl.it/repls/JadedHeartfeltDeclaration) – U13-Forward Aug 29 '18 at 01:41
  • Maybe a [defaultdict](https://docs.python.org/3/library/collections.html#collections.defaultdict) would be useful: `d = defaultdict(lambda: [])`. – Klaus D. Aug 29 '18 at 01:46
  • Your attempts are all copying the list, and then making three references to that copy, which isn’t any better than just making three references to the original list. If you move the `deepcopy` _outside_ the multiplication… but you’re still better off using a comprehension in the first place – abarnert Aug 29 '18 at 02:21

1 Answers1

1

Try a list comprehension:

keys = [1, 2, 3]
d = dict(zip(keys, [[] for _ in keys]))
d[1].append(100)

As per abarnert's comment, you could make your code even simpler by using a dictionary comprehension:

keys = [1, 2, 3]
d = {key:[] for key in keys}
d[1].append(100)

Calling d with both options gives the following output:

{1: [100], 2: [], 3: []}

Chillie
  • 1,356
  • 13
  • 16