close

[Solved] Python Key =0 – Can’t find Dict in code

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Python Key =0 – Can’t find Dict in code in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Python Key =0 – Can’t find Dict in code Error Occurs?

Today I get the following error Python Key =0 – Can’t find Dict in code in python.

How To Solve Python Key =0 – Can’t find Dict in code Error ?

  1. How To Solve Python Key =0 – Can't find Dict in code Error ?

    To Solve Python Key =0 – Can't find Dict in code Error 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.

  2. Python Key =0 – Can't find Dict in code

    To Solve Python Key =0 – Can't find Dict in code Error 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.

Solution 1

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 KeyErrorself.adj[0].append(edge) will create a list automatically to append to.

Solution 2

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)
.
.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read