-1

i want to remove empty dict from nested dict and list dict

input = {'a':'sd','b':{'c':'fd','f':{},'d':'sdsd','j':[{'a':'gg'},{'a':'oio'},{'a':{}}]},'h':''}

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"}}
Ranjan
  • 13
  • 3
  • 2
    Possible duplicate of [How to avoid "RuntimeError: dictionary changed size during iteration" error?](https://stackoverflow.com/questions/11941817/how-to-avoid-runtimeerror-dictionary-changed-size-during-iteration-error) – chickity china chinese chicken Jan 12 '23 at 05:20

1 Answers1

0

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

blhsing
  • 91,368
  • 6
  • 71
  • 106