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
.
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(...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.