Python Key Error=0 - Can't find Dict error in code

The Solution to Python Key Error=0 - Can't find Dict error in code is


The error you're getting is that self.adj doesn't already have a key 0. You're trying to append to a list that doesn't exist yet.

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

self.adj = {}

with this:

self.adj = defaultdict(list)

You'll 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.

~ Answered on 2014-04-25 15:48:19


Most Viewed Questions: