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