尝试访问我的字典时,我继续遇到关键错误

I continue to get a key error when trying to access my dictionary

我正在尝试使用 get_weight 方法打印图顶点的权重。

当我尝试像这样访问它时:

test.final.vert_dict[1].get_weight(Vertex(2)) 

我收到“KeyError: 2”

但是如果我尝试通过 for 循环访问权重:

for key in test.final.vert_dict[1].adjacent:
        print(test.final.vert_dict[1].get_weight(key)) 

我能够得到它们,包括密钥 2 的权重。
'key'和'Vertex(2)'的类型是一样的。我不确定为什么当我以一种方式访问​​它时会出现关键错误,而当我以另一种方式访问​​它时却不会。请帮忙。

class Vertex:
  def __init__(self, node):
    self.id = node
    self.adjacent = {}

  def __str__(self):
    return str(self.id) + ' adjacent: ' + str([x.id for x in self.adjacent])

  def add_neighbor(self, neighbor, weight=0):
    # print("This is add_neighbor type"+str(type(neighbor)))
    self.adjacent[neighbor] = weight

  def get_connections(self):
    return self.adjacent.keys()  

  def get_id(self):
    return self.id

  def get_weight(self, neighbor):
    # print("This is get_weight type"+str(type(neighbor)))
    return self.adjacent[neighbor]



class Graph:
  def __init__(self):
    self.vert_dict = {}
    self.num_vertices = 0


  def add_vertex(self, node):
    self.num_vertices = self.num_vertices + 1
    new_vertex = Vertex(node)
    self.vert_dict[node] = new_vertex
    return new_vertex

  def get_vertex(self, n):
    if n in self.vert_dict:
        return self.vert_dict[n]
    else:
        return None

  def add_edge(self, frm, to, cost = 0):
    # if cost < 0:
    #   self.remove_edge(frm, to)
    #   return

    if frm not in self.vert_dict:
      self.add_vertex(frm)
    if to not in self.vert_dict:
      self.add_vertex(to)

    self.vert_dict[frm].add_neighbor(self.vert_dict[to], cost)
    self.vert_dict[to].add_neighbor(self.vert_dict[frm], cost)

  def get_vertices(self):
    return self.vert_dict.keys()



  # def remove_edge(self, frm, to):
  #     if frm or to not in self.vert_dict:
  #         return
  #     self.vert_dict[frm]
    

if __name__ == '__main__':
    
  test = MakeGraph()
  h = test.formatfile("topology.txt")
  test.buildgraph(h)

  # print(test.final.vert_dict[1].get_weight(Vertex(2)))


  for key in test.final.vert_dict[1].adjacent:
    print(test.final.vert_dict[1].get_weight(key))

您正在使用 class Vertex 的实例作为密钥。由于您尚未为 class 实现 __hash____eq__,它将遵循 Python 对象的默认行为:散列将是实际实例的 id 和两个只有当顶点是同一个对象时,它们才会被认为是相等的。

试试看:

one_vertex = Vertex(2)
another_vertex = Vertex(2)

are_they_the_same = one_vertex == another_vertex
print(are_they_the_same) # this will print false

现在,无论您在 创建 图表时使用了 Vertex 的哪个实例,都将与您新创建的 Vertex(2) 完全不同。因为那现在是一个不同的顶点,它不在你的 vert_dict 中,这就是你得到一个关键错误的原因。

长话短说,你能做些什么?

您可以重写您的图 class 以便您的图 class 通过节点 ID 而不是实际对象来查找节点。

可以 也为你的 Vertex class 实现不同的 __hash____eq__ 但在这种情况下我认为这不是一个好想法,因为你的顶点是 可变的 :你可以向它们添加东西(比如邻居),然后即使顶点 class 的两个实例具有相同的 id,它们也不应该被认为是平等的。