Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python recursion to remove dict keys

i want to remove empty dict from nested dict

input = ss = {"a":"12","b":{"f":"34","z":{}}}

def recurfun(dict_data):
    for key,values in ss.items():
        if isinstance(values, dict) and values == {}:
            del ss[key]
        if isinstance(values, dict):
            recurfun(values)
    return ss
recurfun(ss)

error message is "dictionary changed size during iteration"

output_should_be = {"a":"12","b":{"f":"34"}}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Instead of deleting keys in-place, you can build a new dict using a dict comprehension with an if clause to filter out values of an empty dict:

def recurfun(d):
    return {k: recurfun(v) if isinstance(v, dict) else v for k, v in d.items() if v != {}}

Demo: https://replit.com/@blhsing/SelfreliantWonderfulBlogware

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading