Make an array class using dictionaries only
<p>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.).</p>

<p>I am facing difficulty in coding such a program.</p>

<p>This is my code:</p>

<pre><code>class array(object):
    def __init__(self):
        self.dic={}

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

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

    def __getitem__(self,key):
        if key not in self.dic.keys():
            raise KeyError
        return self.dic[key]
</code></pre>

<p>I want the program to work this way:</p>

<pre><code>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
</code></pre>

<p>Any suggestions, advice. :)</p>

<p>There are quite a few issues with your class definition:</p>

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

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

<pre><code>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())])
</code></pre>

python dictionary