keyerror – Python Key Error=0 – Cant find Dict error in code

keyerror – Python Key Error=0 – Cant find Dict error in code

The error youre getting is that self.adj doesnt already have a key 0. Youre trying to append to a list that doesnt exist yet.

Consider using a defaultdict instead, replacing this line (in __init__):

self.adj = {}

with this:

self.adj = defaultdict(list)

Youll need to import at the top:

from collections import defaultdict

Now rather than raise a KeyError, self.adj[0].append(edge) will create a list automatically to append to.

The defaultdict solution is better.
But for completeness you could also check and create empty list before the append.
Add the + lines:

+ if not u in self.adj.keys():
+     self.adj[u] = []
  self.adj[u].append(edge)
.
.

keyerror – Python Key Error=0 – Cant find Dict error in code

keyerror – Python Key Error=0 – Cant find Dict error in code

It only comes when your list or dictionary not available in the local function.

Leave a Reply

Your email address will not be published. Required fields are marked *