Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

python - How to remove empty or None fields in deeply nested dictionary of unknown depth?

I have a dictionary of deeply nested dictionaries and I am trying to remove all k-v pairs that are None or "". The below dictionary d is an example of the input.

d = { 
  "1": {
    "1_1": 'a real value',
    "1_2": ""
    },
   "2": None,
   "3": {
     "3_1": {
       "3_2": None
     }
   }
}

Normally, to remove empty fields in a dictionary, the command {k:v for k,v in d.items() if v} does the job. But in this case, I want to remove all the nested dictionaries whose values are empty or null, and I can't figure out how to do this. Any ideas?

After d passes through this transformation, all the empty dictionaries whose values are empty should be gone. It should look like this:

{ 
  "1": {
    "1_1": 'a real value',
    }
}
question from:https://stackoverflow.com/questions/65944618/how-to-remove-empty-or-none-fields-in-deeply-nested-dictionary-of-unknown-depth

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use recursion with a dictionary comprehension:

d = {'1': {'1_1': 'a real value', '1_2': ''}, '2': None, '3': {'3_1': {'3_2': None}}}
def get_d(d):
  return {a:c for a, b in d.items() if (c:=(b if not isinstance(b, dict) else get_d(b)))}

print(get_d(d))

Output:

{'1': {'1_1': 'a real value'}}

Note: this solution uses Python's assignment expressions (:=) available in versions >= 3.8. For a solution that does not use this paradigm, please see @Anonymous's answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...