Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

basically I have been racking my brains for a good while now as to why my code is not working, I have tested parts separately and have look throughout the web to see if it can help, to no avail. I am getting an error that the traceback is:

Traceback (most recent call last): File "yes2.py", line 62, in <module> g.add_edge(row_index,col_index, b) File "yes2.py", line 27, in add_edge self.adj[u].append(edge)  KeyError: 0 

The two parts with errors are

    def add_edge(self, u, v, w=0):      if u == v:          raise ValueError("u == v")      edge = Edge(u,v,w)      redge = Edge(v,u,0)      edge.redge = redge      redge.redge = edge      self.adj[u].append(edge) #### LINE 27 ####     self.adj[v].append(redge)      self.flow[edge] = 0      self.flow[redge] = 0  

and

g = FlowNetwork() map(g.add_vertex, ['0','1','2','3','4','5','6']) with open('network.txt', "r") as file: for row_index, row in enumerate(file):     for col_index, value in enumerate(row.split(",")):         b = int(value)         if b != 0:             g.add_edge(row_index,col_index, b) ### LINE 62 #### 

And here is the completed code, as without this it may be difficult to see what is happening

class Edge(object): def __init__(self, u, v, w):     self.source = u     self.sink = v      self.capacity = w  def __repr__(self):      return "%s->%s:%s" % (self.source, self.sink, self.capacity)   class FlowNetwork(object):  def __init__(self):      self.adj = {}      self.flow = {}   def add_vertex(self, vertex):      self.adj[vertex] = []   def get_edges(self, v):      return self.adj[v]   def add_edge(self, u, v, w=0):      if u == v:          raise ValueError("u == v")      edge = Edge(u,v,w)      redge = Edge(v,u,0)      edge.redge = redge      redge.redge = edge      self.adj[u].append(edge)      self.adj[v].append(redge)      self.flow[edge] = 0      self.flow[redge] = 0   def find_path(self, source, sink, path):      if source == sink:          return path      for edge in self.get_edges(source):          residual = edge.capacity - self.flow[edge]          if residual > 0 and not (edge,residual) in path:              result = self.find_path( edge.sink, sink, path + [(edge,residual)] )              if result != None:                  return result   def max_flow(self, source, sink):      path = self.find_path(source, sink, [])      while path != None:          flow = min(res for edge,res in path)          for edge,res in path:              self.flow[edge] += flow              self.flow[edge.redge] -= flow          path = self.find_path(source, sink, [])      return sum(self.flow[edge] for edge in self.get_edges(source))   g = FlowNetwork() map(g.add_vertex, ['0','1','2','3','4','5','6']) with open('network.txt', "r") as file: # enumerate allows you to iterate through the list with an index and an object for row_index, row in enumerate(file):     # split allows you to break a string apart with a string key     for col_index, value in enumerate(row.split(",")):         #convert value from string to int         b = int(value)         if b != 0:             g.add_edge(row_index,col_index, b)  print g.max_flow('1','6') 

Many thanks for your time, much appreciated.

like image 414
user3573321 Avatar asked Apr 25 '14 15:04

user3573321


People also ask

How do you fix key errors in Python?

How to Fix the KeyError in Python Using the in Keyword. We can use the in keyword to check if an item exists in a dictionary. Using an if...else statement, we return the item if it exists or return a message to the user to notify them that the item could not be found.

How does Python handle key dictionary errors?

The Usual Solution: . get() If the KeyError is raised from a failed dictionary key lookup in your own code, you can use . get() to return either the value found at the specified key or a default value.

Why am I getting a key error in Python?

A Python KeyError occurs when you attempt to access an item in a dictionary that does not exist using the indexing syntax. This error is raised because Python cannot return a value for an item that does not exist in a dictionary. The keys are “name”, “price”, and “RAM”.

How do you check if a key exists in a dictionary python?

Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.


2 Answers

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.

like image 81
mhlester Avatar answered Oct 03 '22 13:10

mhlester


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) . . 
like image 33
gaoithe Avatar answered Oct 03 '22 12:10

gaoithe