title: How to iterate over defaultdict?
body: <p>I have the following code which makes topological order:</p>
  
  <pre><code>from collections import defaultdict 
  
  class Graph: 
      def __init__(self): 
          self.graph = defaultdict(list)
          self.V = 0  #number of nodes
  
      def addEdge(self,u,v): 
          self.graph[u].append(v) 
          self.V = self.V + 1
  
      def topologicalSortUtil(self,v,visited,stack): 
  
          visited[v] = True
  
          for i in self.graph[v]: 
              if visited[i] == False: 
                  self.topologicalSortUtil(i,visited,stack) 
  
          stack.insert(0,v) 
  
      # topologicalSortUtil() 
      def topologicalSort(self): 
          # Mark all the vertices as not visited 
          visited = [False]*self.V 
          stack =[] 
  
          for i in range(self.V): 
              if visited[i] == False: 
                  self.topologicalSortUtil(i,visited,stack) 
  
          print stack 
  
  g= Graph() 
  g.addEdge(5, 2); 
  g.addEdge(5, 0); 
  g.addEdge(4, 0); 
  g.addEdge(4, 1); 
  g.addEdge(2, 3); 
  g.addEdge(3, 1); 
  
  g.topologicalSort() 
  </code></pre>
  
  <p>It gives:</p>
  
  <pre><code>[5, 4, 3, 2, 1, 0]
  </code></pre>
  
  <p>Now, I want my code to be able to handle with strings as keys:</p>
  
  <pre><code>g.addEdge('f', 'c')
  g.addEdge('f', 'a')
  g.addEdge('e', 'a')
  g.addEdge('e', 'b')
  g.addEdge('c', 'd')
  g.addEdge('d', 'b')
  </code></pre>
  
  <p>(just change the digits to letters... 0='a', 1='b' etc..)
  However this doesn't work.</p>
  
  <p>It should give:</p>
  
  <pre><code>['f', 'e', 'd', 'c', 'b', 'a']
  </code></pre>
  
  <p>The problem is here:</p>
  
  <pre><code>for i in range(self.V):
      if visited[i] is False:
          self.topologicalSortUtil(i, visited, stack)
  </code></pre>
  
  <p>The code iterates over <code>range</code> and not over the actual node keys.</p>
  
  <p>I tried to convert it to:</p>
  
  <pre><code>for i in self.graph.items():
  </code></pre>
  
  <p>but it doesn't work.</p>
  
  <pre class="lang-none prettyprint-override"><code>TypeError: list indices must be integers or slices, not tuple
  </code></pre>
  
  <p>How can I fix this?</p>