0

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.

Yash
  • 81
  • 7
  • 1
    There is no specific function for that. You have to iterate through the dict entries and either remove the unwanted ones or build a new dict, usually with a dict comprehension. – Michael Butscher Nov 02 '22 at 09:23

2 Answers2

1

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 }

Claudio
  • 7,474
  • 3
  • 18
  • 48
1

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 }
Abirbhav G.
  • 369
  • 3
  • 14
  • Usage of `is not None` works, but ... comparisons using `is` are generally not a good idea in Python. – Claudio Nov 02 '22 at 09:41
  • `None` is a singleton object. There is only ever 1 `None`. So comparing against it with `is` is the more Pythonic way of checking for `None`. https://stackoverflow.com/a/3257957/5901382 – Abirbhav G. Nov 02 '22 at 09:43
  • Yes, you are right. None is an exception from the general rule. – Claudio Nov 02 '22 at 09:54