0

I am trying to loop over a dictionary and call a function on each key.

If the function does not return None entry for that key, I want the output to be appended to a list and I also want that key to be appended to a second list.

Here is my code:

    output_list = []
    key_list =[]

    for i in dict.keys():
        if obj.method(i):
            output_list.append(obj.method(i))
            key_list.append(i)

    return output_list
    return key_list

However, for some reason the second list, key_list, is never populated - can you not have two statements below an if like the above?

The reason that I am doing this is that I want to eventually produce an output where each key of the dict is listed alongside it's associated function ouput, whenever the output is not None.

Charon
  • 2,344
  • 6
  • 25
  • 44
  • possible duplicate of [How can I return two values from a function in Python?](http://stackoverflow.com/questions/9752958/how-can-i-return-two-values-from-a-function-in-python) – YXD Mar 14 '14 at 14:33

1 Answers1

1

key_list is being populated, however you can only return once from a function.

You can return a tuple of results though to return multiple variables. Change:

return output_list
return key_list

to

return output_list, key_list

And in the calling code do:

output_list, key_list = my_function(...)
YXD
  • 31,741
  • 15
  • 75
  • 115