[英]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.