In python, append dictionary value with each element in array
<p>Hi and thank you so much for your help!</p>

<p>I am sure this is a dumb question but I am trying to append a dictionary value with the elements within an array. Right now I can only get it to load the entire array of elements as one entry instead of separate values. Sorry if I am not explaining this well. Here is an example:</p>

<pre><code>Array = [4,5,6]
dictionary {'index'} = [1,2,3]
</code></pre>

<p>Here is what I am doing and it's wrong</p>

<pre><code>dictionary['index'].append(array)
</code></pre>

<p>It's wrong because if I inquiry how many elements are in dictionary ['index'][1] it returns 1 instead of 3. Look here:</p>

<pre><code>print range(len(dictionary['index'][0]))
</code></pre>

<p>The answer is 3, thats 1 2 and 3. however!</p>

<pre><code>print range(len(dictionary['index'][1]))
</code></pre>

<p>The answer is 1, [4,5,6]. I must be loading the array in incorrectly. Does anyone know what I am doing wrong? Thanks!</p>

<p>If you want to append an entire list to an existing list, you can just use <code>extend()</code>:</p>

<pre><code>a = [4,5,6]
d = {'index': [1,2,3]}
d['index'].extend(a)
</code></pre>

<p>output:</p>

<pre><code>{'index': [1, 2, 3, 4, 5, 6]}
</code></pre>

<p>If you want to end up with a list containing two lists, [1,2,3] and [4,5,6], then you should consider how the dictionary value is initially created. You can do:</p>

<pre><code>d['index'] = [1,2,3]
d['index'] = [d['index']]
d['index'].append([4,5,6])
</code></pre>

<p>output:</p>

<pre><code>{'index': [[1, 2, 3], [4, 5, 6]]}
</code></pre>

python arrays dictionary append