0

I was hoping to gather insight about what I am trying to do using python: So I have this array in my function that dynamically changes everytime. What I want to do is gather the multi-dimensional array data and put them together as a single array. Here is what I have been trying so far.

Code:

def myFunction(data,topic)
         data = data
         topic = topic
         pushed_data = []

         for ctr in range(len(data)):

             new_data = pushed_data.append([ctr]['topic'])

         print new_data

Output:

None

So I believe "None" corresponds to the array being unsuccessfully pass to the empty array. So what I would like to have as the contents would be

Preferred Output:

['topic1','topic2','topic3']

So If it is possible to achieve this without using additional python libraries then that would be great.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Alfred M.
  • 159
  • 2
  • 14

1 Answers1

1

The main issue in your code comes from the line -

new_data = pushed_data.append([ctr]['topic'])

list.append() is an in place operation, it does not return anything, which means it returns None by default and that is why new_data is always None. Instead of that , you just want to do - pushed_data.append(...) - without assigning the return variable to anything. And then you want to print pushed_data , not new_data .

Secondly, I am not really sure what this is supposed to be -

[ctr]['topic']

This should ideally give you an error like - list indices must be integers, not str - If you want to get the topic index from each row in data , then you should do -

pushed_data.append(data[ctr][topic])

If data contains dictionaries (if data is a list of dictionaries) and you really want the value for key 'topic' , use - data[ctr]['topic'] instead.

An easier way to do this would be to directly iterate over the elements of data instead of taking its length and iterating over the indices , since you do not really need the indices for anything else. Example -

for elem in data:
    new_data = pushed_data.append(elem[topic])

Also, you do not need to do -

data = data
topic = topic

That does not do anything.

Same can be achieved through list comprehension as -

def myFunction(data,topic)
     pushed_data = [elem[topic] for elem in data]
     print(pushed_data)
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176