Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace empty dicts in nested dicts

Tags:

python

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?

like image 238
Tornado547 Avatar asked Jun 27 '18 18:06

Tornado547


2 Answers

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

like image 181
Netwave Avatar answered Sep 23 '22 05:09

Netwave


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': ''}}
like image 28
DEEPAK SURANA Avatar answered Sep 24 '22 05:09

DEEPAK SURANA