Joel Persinger Joel Persinger - 1 year ago 281
Python Question

In python, append dictionary value with each element in array

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


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!

Answer Source

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]}


{'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']]


{'index': [[1, 2, 3], [4, 5, 6]]}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download