title: Iterating over dictionary using __getitem__ in python
body: <p>I've implemented a python class to generate data as follows: </p>
  
  <pre><code>class Array:
      def __init__(self):
          self.arr = [1,2,3,4,5,6,7,8]
  
      def __getitem__(self,key):
          return self.arr[key]
  
  a = Array()
  for i in a:
      print(i, end = " ")
  </code></pre>
  
  <p>It runs as expected and I get following </p>
  
  <pre><code>1 2 3 4 5 6 7 8
  </code></pre>
  
  <p>However, I want to do the same thing for dictionary. Why am I not able to iterate over dictionary like this?</p>
  
  <pre><code>class Dictionary:
      def __init__(self):
          self.dictionary = {'a' : 1, 'b' : 2, 'c': 3}
  
      def __getitem__(self,key):
          return self.dictionary[key]
  d = Dictionary()
  for key in d:
      print(key, d[key], end=" ")
  </code></pre>
  
  <p>I expect following output</p>
  
  <pre><code>a 1 b 2 c 3
  </code></pre>
  
  <p>But when I run above code, I get following error : </p>
  
  <pre><code>Traceback (most recent call last):
  
    File "&lt;ipython-input-33-4547779db7ec&gt;", line 8, in &lt;module&gt;
      for key in d:
  
    File "&lt;ipython-input-33-4547779db7ec&gt;", line 6, in __getitem__
      return self.dictionary[key]
  
  KeyError: 0
  </code></pre>
  
  <p>We can iterate over normal dictionary like this : <code>for key in d</code>. This iterates over all the keys, is it not possible to iterate like this using <code>__getitem__()</code>?</p>