简体   繁体   中英

Remove Dictionary Key, if Value is empty

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM