Kamil Kamili Kamil Kamili - 11 days ago 5x
Python Question

Make an array class using dictionaries only

I am a student who is new to python. I am trying to define an array class below which uses a dictionary as its only member variable. I am assuming that Python implements dictionaries as the only structured type (i.e., there is no array, list, tuple, etc.).

I am facing difficulty in coding such a program.

This is my code:

class array(object):
def __init__(self):

def __init__(self,diction):
self.dic = {}
for x in diction:

def __setitem__(self,key,value):

def __getitem__(self,key):
if key not in self.dic.keys():
raise KeyError
return self.dic[key]

I want the program to work this way:

a = array('a','b','c') #------output------

print(a) # ['a', 'b', 'c']

print(a[1]) # b

a[1] = 'bee'

print(a) # ['a', 'bee', 'c']

a[3] = 'day'

print(a) # ['a', 'bee', 'c', 'day']

print(a[6]) # IndexError exception

Any suggestions, advice. :)


There are quite a few issues with your class definition:

  • array is already a data structure: better to rename using the proper Python class-naming conventions (MyClass).
  • You cannot overload function definitions: better to use an unpacking operator (*) to extract all (if any) arguments.
  • You cannot append to a dictionary: you need to assign to a key.
  • Your call to print will display a generic class name, since you don't specify a __str__ magic method. Since a dict is unordered, I did some funny business here to make it display as sorted, though I'm sure there's a better way.
  • No need to raise a KeyError in __getitem__, since this will be raised anyway.
  • Finally, I corrected your spacing.

Note that I've only implemented the methods necessary to make your test cases work.

class MyArray(object):
    def __init__(self, *diction):
        self.dic = {}
        for i, x in enumerate(diction):
            self.dic[i] = x

    def __setitem__(self, key, value):
        self.dic[key] = value

    def __getitem__(self, key):
        return self.dic[key]

    def __str__(self):
        return str([self.dic[i] for i in sorted(self.dic.keys())])