Q:

Depth First Search in python Error : Key Error 7

I have written following python program to perform a DFS for the given graph, but after execution it gives the error : Key Error 7. What is wrong in my code?
output=[]
graph = {
            9:[8,7,6],
            8:[5,4],
            6:[3,2],
            5:[1,0]
        }

def dfs(graph,root):
    stack=[]
    visited=set()

    stack.append(root)
    output.append(str(root))
    visited.add(root)

    while not(stack==[]):
        for item in graph[root]:

            if item not in visited:
                stack.append(item)
                visited.add(item)
                output.append(str(item))

            if set(graph[item]).union(visited)==visited:
                stack.pop(-1)
                root=stack[len(stack)-1]
                continue

            root=item

dfs(graph,9)
print(" ".join(output))

Still the problem is not solved after adding suggestions given by @amit i have written the following code and it is giving incorrect output, please help!
output=[]
graph = {
           1:[2,3],
           2:[4,5],
           3:[6,7],
           4:[],
           5:[],
           6:[],
           7:[]
        }

def dfs(graph,root):
    stack=[]
    visited=set()

    stack.append(root)
    output.append(str(root))
    visited.add(root)

    while not(stack==[]):
        for item in graph[root]:

            if item not in visited:
                stack.append(item)
                visited.add(item)
                output.append(str(item))

            if set(graph[item]).union(visited)==visited:
                stack.pop(-1)
                if not(stack==[]):
                    root=stack[len(stack)-1]
                else:
                    break
                continue

            root=item

dfs(graph,1)
print(" ".join(output))

A:

Your graph implementation does not have nodes with d_out(v)=0 as keys.
So, in this line:
        if set(graph[item]).union(visited)==visited:

When you put 7 (or 4) as item, you try to access graph[7] - but there is no such key.
You can overcome it by either changing the graph implementation to have a key:[] for all keys (including those with no out-edges), or by adding a check to the condition to check if item is in graph before attempting to access it.

