I have a nested dictionary whose structure looks like this
{"a":{},"b":{"c":{}}}
Every key is a string and every value is a dict.
I need to replace every empty dict with ""
. How would I go about this?
Use recursion:
def foo(the_dict):
if the_dict == {}:
return ""
return {k : foo(v) for k,v in the_dict.items()}
Here you have a live example
Checking values for an empty dict recursively, and replacing with empty string if so.
>>> d = {"a":{},"b":{"c":{}}}
>>> def replace_empty(d):
... for k, v in d.items():
... if not bool(v):
... d[k] = ""
... else:
... d[k] = replace_empty(v)
... return d
>>> replace_empty(d)
{'a': '', 'b': {'c': ''}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With