yaron0
yaron0

Reputation: 67

Key error (0,0) in python

I am trying to build a graph that I used in dijkstra. I wrote this code:

def build_graph(self,board):
    G={} # dictionary that use as graph for dijkstra
    len_x=len(board)
    len_y=len(board[0])
    for x in range(0,len(board)):
        for y in range(0,len(board[x])):
            if board[x][y]!=99:
                if (len_y>(y-1)>=0):
                    if board[x][y-1]==90:
                        G[(x,y)]={(x,y-1):6 } # [location ,weight]
                    if board[x][y-1]==10 or board[x][y+1]==12:
                        G[(x,y)]={(x,y-1):1 }  # case 10 or 12 --> clean path
                if (len_y>(y+1)>=0):
                    if board[x][y+1]==90:       
                        G[(x,y)][(x,y+1)]=6
                    if board[x][y+1]==10 or board[x][y+1]==12:     
                        G[(x,y)][(x,y+1)]=1

                if (0<=(x+1)<len_x):
                    if board[x+1][y]==90:
                        G[(x,y)][(x+1,y)]=6
                    if board[x+1][y]==10 or board[x+1][y]==12:     
                         G[(x,y)][(x+1,y)]=1

                if (0<=(x-1)<len_x):
                    if board[x-1][y]==90:
                        G[(x,y)][(x-1,y)]=6
                    if board[x-1][y]==10 or board[x-1][y]==12 :    
                         G[(x,y)][(x-1,y)]=1


    return G       

And key error (0,0) at this statement:

G[(x,y)][(x,y+1)]=1 and I don't know why I got it?

Upvotes: 0

Views: 2319

Answers (1)

pneumatics
pneumatics

Reputation: 2885

You're trying to use the dictionary at G[(0, 0)] before it's created. Try assigning it an empty dictionary at the top of the inner loop, like this:

def build_graph(self,board):
    G={} # dictionary that use as graph for dijkstra
    len_x=len(board)
    len_y=len(board[0])
    for x in range(0,len(board)):
        for y in range(0,len(board[x])):
           G[(x,y)] = {}
           ...

Upvotes: 1

Related Questions