title: Depth First Search in python Error : Key Error 7
body: <p><img src="https://i.stack.imgur.com/D61s7.png" alt="enter image description here"></p>
  
  <p>I have written following python program to perform a <strong>DFS</strong> for the given graph, but after execution it gives the error : <strong>Key Error 7</strong>. What is wrong in my code?</p>
  
  <pre><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))
  </code></pre>
  
  <hr>
  
  <p>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!</p>
  
  <pre><code>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))
  </code></pre>