1

Hi and thank you so much for your help!

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:

Array = [4,5,6]
dictionary {'index'} = [1,2,3]

Here is what I am doing and it's wrong

dictionary['index'].append(array)

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

print range(len(dictionary['index'][0]))

The answer is 3, thats 1 2 and 3. however!

print range(len(dictionary['index'][1]))

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

Joel Persinger
  • 81
  • 1
  • 2
  • 8
  • 1
    Your example is wrong, `dictionary {'index'} = [1,2,3]` throws InvalidSyntax – iScrE4m Sep 07 '16 at 16:41
  • 2
    This question is rather unclear. Can you provide a working code example? It looks like the second line is supposed to be `dictionary['index'] = [[1, 2, 3]]` (note the square brackets instead of the curly braces before the `=` and the additional pair of square brackets after). After this is fixed, your example doesn't show the behaviour you claim (try it!), so you are apparently doing something else. – Sven Marnach Sep 07 '16 at 16:43
  • Moreover, the first and second elements of your `dictionary['index']` are integers, so you can't get their length. Maybe you wanted to write `len(range(dictionary['index'][0]))`. – cphyc Sep 07 '16 at 16:43
  • My guess is that you modify the list `Array` (which is a list, not an array) after appending it to the dictionary value. No copy will be made when you append it, so later modifications to `Array` will affect the value in the dict. – Sven Marnach Sep 07 '16 at 16:47

1 Answers1

10

If you want to append an entire list to an existing list, you can just use extend():

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

output:

{'index': [1, 2, 3, 4, 5, 6]}

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:

d['index'] = [1,2,3]
d['index'] = [d['index']]
d['index'].append([4,5,6])

output:

{'index': [[1, 2, 3], [4, 5, 6]]}
denvaar
  • 2,174
  • 2
  • 22
  • 26