如果值为空,则删除字典键

Remove Dictionary Key, if Value is empty

目标:有一个 dictionary-comprehension 删除给定的键,如果它的相应值为 "empty".

Empty 表示诸如:[], 0, None, 0.0, "" 等的任何内容

代码:

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

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

如果还有什么我可以添加到 post 以帮助进一步澄清,请告诉我。

这个

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

是set-comprehension,如果需要dict-comprehension做

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

有关 Dict Comprehensions

的进一步讨论,请参阅 PEP 274

您可以使用 python Dictionary(get)

的内置方法
{key:value for key,value in thisdict.items() if thisdict.get(key)}