I have return statement within a recursive function that looks like this:
def recursive_function(data):
....
return {f'uid': uid,'title': title, 'string': string,'create-time': create_time, 'edit-time': edit_time, 'children': children, 'refs': refs}
Sometimes some of these values can be None (ex: when the title has a value, the string's value will be None, and vice-versa). The application I'm using does not recognize keys with None values, how do I prevent those keys from returning when the values are None?
Thank you in advance.
CodePudding user response:
You can't directly get non-None
values from a dict directly. You can use a dictionary comprehension to retrieve the non-None
values yourself instead.
def recursive_function(data):
...
original_dict = {'uid': uid,'title': title, 'string': string,
'create-time': create_time, 'edit-time': edit_time,
'children': children, 'refs': refs}
return { key: value for key, value in
original_dict.items() if value is not None }
CodePudding user response:
You can achieve this using dictionary comprehension:
return {key:value for key,value in {f'uid': uid,'title': title, 'string': string,'create-time': create_time, 'edit-time': edit_time, 'children': children, 'refs': refs}.items() if value is not None }