0

I have the following function that returns data:

def get_comments():
 for i in data:
  comment_data = i['comments']
  for z in comment_data:
   comments = comment_data['data']
   for j in comments:
    comment = j['message']
    print(comment)

I would like to save the output of this function to a variable. I'm using print instead of return (in the function get_comments) since, return only returns the final row of my data. This is what i have tried to account for that:

def hypothetical(x):
return x

z = hypothetical(get_comments())
print(z)

However the output of the variable z is "None".

When i try some other value(i.e.):

 z = hypothetical(5)
 print(z)

z is equal to 5 of course.
Thanks

CS.py
  • 43
  • 6
  • If `print()` prints the data you want, then `return` will return that same data – Tom Burrows Aug 04 '20 at 12:47
  • Hi Tom, it does not, it only returns the last row of my data – CS.py Aug 04 '20 at 12:48
  • 1
    Ah I think I understand you then. Instead of `print`ing each line, you need to add it to a different data structure (such as a list) and return the whole list at the end of `get_comments()`. – Tom Burrows Aug 04 '20 at 12:49

1 Answers1

5

Instead of printing each line, you need to add it to a different data structure (such as a list) and return the whole list at the end of get_comments().

For example:

def get_comments():
  to_return = []
  for i in data:
    comment_data = i['comments']
    for z in comment_data:
      comments = comment_data['data']
      for j in comments:
        comment = j['message']
        to_return.append(comment)
  return to_return

If you want to get a bit more advanced, you can instead create a generator using yield:

def get_comments():
  for i in data:
    comment_data = i['comments']
    for z in comment_data:
      comments = comment_data['data']
      for j in comments:
        comment = j['message']
        yield comment

Then you can iterate over get_comments() and it will go back into the generator each time to get the next comment. Or you could simply cast the generator into a list with list(get_comments()) in order to get back to your desired list of comments.

Refer to this excellent answer for more about yield and generators.

Tom Burrows
  • 2,225
  • 2
  • 29
  • 46