python recursion to remove dict keys

Advertisements

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"}}

>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

Leave a ReplyCancel reply