[英]This Python script returns “KeyError: '6'” and I don't know why
这个脚本是我的一个任务的答案。 问题出现在我评论为“任务 3”的部分下方。 我的代码工作得非常好,或者至少看起来是这样,因为它在图中打印出正确的节点。 但是,由于某种原因,我得到“KeyError:'6'”,我不明白为什么。
这是我的整个脚本:
# Task 1
# The answer is D, All of the above
# Task 2
def binary_tree(r):
return [r, [], []]
def get_left_child(root):
return root[1]
def get_right_child(root):
return root[2]
def insert_left_child(root, new_branch):
t = root.pop(1)
if len(t) > 1:
root.insert(1, [new_branch, t, []])
else:
root.insert(1, [new_branch, [], []])
return root
def insert_right_child(root, new_branch):
t = root.pop(2)
if len(t) > 1:
root.insert(2, [new_branch, [], t])
else:
root.insert(2, [new_branch, [], []])
return root
my_tree = binary_tree('a')
insert_left_child(my_tree, 'b')
insert_right_child(my_tree, 'c')
insert_right_child(get_right_child(my_tree), 'd')
insert_left_child(get_right_child(get_right_child(my_tree)), 'e')
print(my_tree, "\nThe answer is C")
# Task 3
class Graph:
graph = dict()
def add_edge(self, node, neighbour):
if node not in self.graph:
self.graph[node] = [neighbour]
else:
self.graph[node].append(neighbour)
def print_graph(self):
print(self.graph)
def breadth_first_search(self, node):
searched = []
search_queue = [node]
while search_queue:
searched.append(node)
node = search_queue.pop(0)
print("[", node, end=" ], ")
for neighbour in self.graph[node]:
if neighbour not in searched:
searched.append(neighbour)
search_queue.append(neighbour)
def build_my_graph2():
my_graph = Graph()
my_graph.add_edge("1", "2")
my_graph.add_edge("2", "3")
my_graph.add_edge("3", "5")
my_graph.add_edge("4", "5")
my_graph.add_edge("5", "6")
my_graph.breadth_first_search("1")
build_my_graph2()
当您调用不在字典中的键时,您会收到 KeyError。 根据您的 add_edge function,您似乎为 1、2、3、4、5 创建了一个键,但您只为 6 添加了一个值。
在这里,您请求键 6 的值,但 6 本身不是键。
for neighbour in self.graph[node]:
每当请求 dict() object(使用格式 a = mydict[key])并且密钥不在字典中时,Python 就会引发 KeyError。
随意阅读更多关于 Python 中的 KeyError 异常的信息: https://realpython.com/python-keyerror/
哪一行代码抛出错误?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.