为什么我在字典的实现中收到Python keyerror?

时间:2014-10-24 18:13:01

标签: python dictionary graph keyerror

出于某种原因,我无法在下图的实现中查找正确的键。由于出现错误的字典实现,我一直得到一个KeyError。我已经研究了几个小时,仍然无法弄清楚问题是什么。

> KeyError                                  Traceback (most recent call
> last)
> C:\Users\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.0.1938.win-x86_64\lib\site-packages\IPython\utils\py3compat.pyc
> in execfile(fname, glob, loc)
>     195             else:
>     196                 filename = fname
> --> 197             exec compile(scripttext, filename, 'exec') in glob, loc
>     198     else:
>     199         def execfile(fname, *where):
> 
> C:\Users\ps5.py in <module>()
>      69     
>      70 
> ---> 71 bigMap = load_map(mapFile)
>      72 
> 
> C:\Users\ps5.py in load_map(mapFilename)
>      51         e1 = WeightedEdge(nx, ny, ex, ey)
>      52         
> ---> 53         g.addEdge(e1)
>      54     return g
>      55     
> 
> C:\Users\graph.py in addEdge(self, edge)
>      74         if not (src.getName() in self.nodes and dest.getName() in self.nodes):
>      75             raise ValueError('Node not in graph')
> ---> 76         self.edges[src].append([dest, (edge.getTotalDistance(), edge.getOutdoorDistance())])
>      77 
>      78     def __str__(self):
> 
> KeyError: <graph.Node object at 0x00000000080B1A90>


class Node(object): 
    def __init__(self, name): 
        self.name = str(name) 
    def getName(self): 
        return self.name
    def __str__(self): 
        return self.name

class Edge(object): 
    def __init__(self, src, dest): 
        self.src = src
        self.dest = dest
    def getSource(self): 
        return self.src
    def getDestination(self): 
        return self.dest 
    def __str__(self): 
        return str(self.src) + '->' + str(self.dest) 

class WeightedEdge(Edge): 
    def __init__(self, src, dest, totalDistance, outdoorDistance): 
        self.src = src
        self.dest = dest 
        self.totalDistance = float(totalDistance) 
        self.outdoorDistance = float(outdoorDistance) 
    def getWeight(self): 
        return self.weight
    def __str__(self): 
        return str(self.src) + '->' + str(self.dest) + ' (' + \
        str(self.totalDistance) + ', ' + str(self.outdoorDistance) + ')'
    def getTotalDistance(self):
        return self.totalDistance 
    def getOutdoorDistance(self): 
        return self.outdoorDistance

class Digraph(object): 
    def __init__(self): 
        self.nodes = set([])
        self.edges = {} 
    def addNode(self, node): 
        if node.getName() in self.nodes: 
            raise ValueError('Duplicate node') 
        else: 
            self.nodes.add(node.getName()) 
            self.edges[node] = [] 
    def addEdge(self, edge): 
        src = edge.getSource() 
        dest = edge.getDestination() 
        if not(src in self.nodes and dest in self.nodes): 
            raise ValueError('Node not in graph') 
        self.edges[src].append(dest) 
    def childrenOf(self, node): 
        return self.edges[node]
    def hasNode(self, node): 
        return str(node) in self.nodes
    def __str__(self): 
        res = ''
        for k in self.edges: 
            for d in self.edges[k]: 
                res = res + str(k) + '->' + str(d) + '\n'
        return res[:-1]

class Graph(Digraph): 
    def addEdge(self, edge): 
        Digraph.addEdge(self, edge)
        rev = Edge(edge.getDestination(), edge.getSource()) 
        Digraph.addEdge(self, rev)

class WeightedDigraph(Digraph): 

    def addEdge(self, edge):
        src = edge.getSource() 
        dest = edge.getDestination()
        if not (src.getName() in self.nodes and dest.getName() in self.nodes): 
            raise ValueError('Node not in graph')
        self.edges[src].append([dest, (edge.getTotalDistance(), edge.getOutdoorDistance())])

    def __str__(self): 
        res = ''
        for k in self.edges: 
            for d in self.edges[k]:
                res = res + str(k) + '->' + str(d[0]) + ' (' + str(float(d[1][0])) + ', ' + str(float(d[1][1])) + ')' + '\n'
        return res[:-1]

    def childrenOf(self, node): 
        children = [] 
        for child in self.edges[node]: 
            children.append(child[0]) 
        return children

def load_map(mapFilename):
    dataFile = open(mapFilename, 'r')
    g = WeightedDigraph() 
    for line in dataFile: 
        nx, ny, ex, ey = line.split() 
        nx = Node(nx) 
        ny = Node(ny) 
        if not g.hasNode(nx): 
            g.addNode(nx) 
        if not g.hasNode(ny): 
            g.addNode(ny)     
        e1 = WeightedEdge(nx, ny, ex, ey)
        g.addEdge(e1) 
   return g

bigMap = load_map(mapFile) 

1 个答案:

答案 0 :(得分:1)

因此,您的错误似乎在WeightedDigraph.addEdge(self, edge)

您传入一个边缘对象并获取源(src = edge.getSource())。通过使用调试器,我能够查看字典self.edges,我发现密钥的格式为{<Node object>: <list>}

实际的调试视图给了我这个:

self.edges = { <__main__.Node object at 0x10f1d4350>: [] }

如果您要将对象用作python dict中的键,则需要包含两个函数:

def __hash__(self)

def __eq__(self, other)

这是一个堆栈溢出问题,可以解决这个问题:Object of custom type as dictionary key

我做了一个快速标记,它似乎解决了你的密钥错误。

此外,我强烈建议使用调试器(pydb(http://bashdb.sourceforge.net/pydb/)是一个这样的调试器,但很多内置在IDE中),因为这是我发现错误的方法。