Dictionary of numpy array in python
<p>I want to create a data structure of empty numpy array something of this sort:</p>

<pre><code>d[1].foo = numpy.arange(x)
d[1].bar = numpy.arange(x)
d[2].foo = numpy.arange(x)
d[2].bar = numpy.arange(x)
</code></pre>

<p>What would be the best option ... a list of dictionaries containing numpy arrays?</p>

<p>If I define a simple class like:     </p>

<pre><code>class MyObj(object):
    pass
     .
</code></pre>

<p>I could create a dictionary with several of these objects:</p>

<pre><code>In [819]: d={1:MyObj(), 2:MyObj()}
</code></pre>

<p>and then assign attributes to each object</p>

<pre><code>In [820]: d[1].foo=np.arange(3)
In [821]: d[1].bar=np.arange(3)
In [822]: d[2].foo=np.arange(3)
In [823]: d[2].bar=np.arange(3)
In [824]: d
Out[824]: {1: &lt;__main__.MyObj at 0xaf20cfac&gt;, 2: &lt;__main__.MyObj at 0xaf20c4cc&gt;}
</code></pre>

<p>Since I didn't define a <code>repr</code> or <code>str</code> the print display isn't very interesting; </p>

<pre><code>In [825]: vars(d[2])
Out[825]: {'bar': array([0, 1, 2]), 'foo': array([0, 1, 2])}
</code></pre>

<p>I could also made a list with these objects</p>

<pre><code>In [826]: dl = [None, d[1], d[2]]
In [827]: dl
Out[827]: [None, &lt;__main__.MyObj at 0xaf20cfac&gt;, &lt;__main__.MyObj at 0xaf20c4cc&gt;]
In [828]: vars(dl[1])
Out[828]: {'bar': array([0, 1, 2]), 'foo': array([0, 1, 2])}
</code></pre>

<p>So both a list and dictionary can be indexed (so can an array); but the <code>.foo</code> syntax is used to access object attributes.</p>

<p>===============</p>

<p>An entirely different way of creating a structure with this kind of access is to use a <code>recarray</code> - this is a numpy array subclass that allows you to access dtype fields with attribute names</p>

<pre><code>In [829]: R=np.recarray((3,), dtype=[('foo','O'),('bar','O')])
In [830]: R
Out[830]: 
rec.array([(None, None), (None, None), (None, None)], 
          dtype=[('foo', 'O'), ('bar', 'O')])
In [831]: R[1].foo=np.arange(3)
In [832]: R[2].bar=np.arange(4)
In [833]: R
Out[833]: 
rec.array([(None, None), (array([0, 1, 2]), None), (None, array([0, 1, 2, 3]))], 
          dtype=[('foo', 'O'), ('bar', 'O')])
</code></pre>

<p>Here I defined the fields as taking object dtype, which allows me to assign anything, including other arrays to each attribute.  But usually the dtype is something more specific like int, float, string.</p>

<p>I can view the <code>foo</code> attribute/field for all items in the array <code>R</code>:</p>

<pre><code>In [834]: R.foo
Out[834]: array([None, array([0, 1, 2]), None], dtype=object)
In [835]: R['bar']
Out[835]: array([None, None, array([0, 1, 2, 3])], dtype=object)
</code></pre>

<p>A <code>recarray</code> has a special method that allows access to the fields via <code>attribute</code> syntax.</p>

python numpy