Python Key Error = 0 - 无法在代码中找到Dict错误

时间:2014-04-25 15:44:25

标签: python keyerror

基本上我已经绞尽脑汁了,为什么我的代码不能正常工作,我已经分别测试了部件并且在整个网络上查看它是否可以提供帮助,但无济于事。 我收到错误回溯:

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

有错误的两个部分是

    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 

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 ####

这是完成的代码,因为没有这个,可能很难看到发生了什么

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

非常感谢你的时间,非常感谢。

4 个答案:

答案 0 :(得分:8)

您遇到的错误是self.adj还没有密钥0。您正试图附加到尚不存在的列表中。

请考虑使用defaultdict替换此行(在__init__中):

self.adj = {}

用这个:

self.adj = defaultdict(list)

您需要在顶部导入:

from collections import defaultdict

现在而不是提出KeyErrorself.adj[0].append(edge)会自动创建一个列表以附加到。{/ p>

答案 1 :(得分:3)

defaultdict解决方案更好。 但为了完整性,您还可以在追加之前检查并创建空列表。 添加+行:

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

答案 2 :(得分:0)

尝试一下:

class Flonetwork(Object):
    def __init__(self,adj = {},flow={}):
        self.adj = adj
        self.flow = flow

答案 3 :(得分:-1)

仅当您的列表或词典在本地功能中不可用时才会出现。