Home > Mobile >  Remove Dictionary Key, if Value is empty
Remove Dictionary Key, if Value is empty

Time:11-18

Goal: Have a dictionary-comprehension that removes a given key, if its respective value is "empty".

Empty means anything such as: [], 0, None, 0.0, "" etc.

Code:

thisdict =  {
  "brand": "Ford",
  "model": "Mustang",
  "year": ''  # [], 0, None, 0.0, "" etc.
}
print(thisdict)

thisdict = {val for key, val in thisdict.items() if val}  # Attempt

Please let me know if there is anything else I can add to post to help further clarify.

CodePudding user response:

This

thisdict = {val for key, val in thisdict.items() if val}

is set-comprehension, if you need dict-comprehension do

thisdict = {key:val for key, val in thisdict.items() if val}

See PEP 274 for further discussion of Dict Comprehensions

CodePudding user response:

You can use built in method of python Dictionary(get)

{key:value for key,value in thisdict.items() if thisdict.get(key)}
  • Related