0

So I am iterating through a "list of lists" of integers in python 3.9.0 as follows:

n = 3
adjList = dict.fromkeys([i for i in range(n)], [])
p = [[1, 0], [2, 0]]
for s, e in p:
   if e not in adjList[s]:
     adjList[s].append(e)

I would expect adjList to result in:

{0: [], 1: [0], 2: [0]}

Instead I get:

>>> adjList
{0: [0], 1: [0], 2: [0]}

Why isn't append modifying the list specified in adjList[i] only where i is the integer key?

I can get it to work by changing adjList[s].append(e) to adjList[s] = adjList[s] + [e].

Nona
  • 5,302
  • 7
  • 41
  • 79
  • 1
    What does your debugger say `adjList` is after the *first* call to `append`? – Scott Hunter Nov 11 '20 at 18:00
  • 2
    `dict.fromkeys` uses the *same list object* for each `dict` value, causing the problem described in the linked duplicate. You can instead use a dict comprehension to build the dictionary: `{i: [] for i in range(n)}`. – Karl Knechtel Nov 11 '20 at 18:00
  • 1
    Do `adjList = {i: [] for i in range(n)}` – azro Nov 11 '20 at 18:01
  • 1
    While it does answer the question, I don't think the current linked question is the corrected dup. It doesn't say anything about `fromkeys` and why it shouldn't be used in this instance. The appropriate dup should be [How do I initialize a dictionary of empty lists in Python?](https://stackoverflow.com/q/11509721/1040092) – Wondercricket Nov 11 '20 at 18:04
  • 1
    @Wondercricket I changed it – juanpa.arrivillaga Nov 11 '20 at 18:06

0 Answers0