简体   繁体   中英

This Python script returns “KeyError: '6'” and I don't know why

This script is the answer to an assignment I have. The problem arises below the section I have commented as "Task 3". My code works perfectly fine, or at least seems to do so, as it prints out the correct nodes in the graph. However, for some reason, I get "KeyError: '6'", and I don't understand why.

Here's my entire script:

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

You get a KeyError when you call for a key that is not in the dictionary. Based on your add_edge function, it looks like you create a key for 1, 2, 3, 4, 5, but you add a value only for 6.

Here you are requesting a value for key 6, but 6 in itself is not a key.

for neighbour in self.graph[node]:

Python raises a KeyError whenever a dict() object is requested (using the format a = mydict[key]) and the key is not in the dictionary.

Feel free to read more about KeyError exceptions in Python here: https://realpython.com/python-keyerror/

Which line of code throws the error?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM