目標:如果其各自的值為"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
如果還有什么我可以添加到帖子中以幫助進一步澄清,請告訴我。
uj5u.com熱心網友回復:
這個
thisdict = {val for key, val in thisdict.items() if val}
是集合理解,如果你需要字典理解做
thisdict = {key:val for key, val in thisdict.items() if val}
有關字典理解的進一步討論,請參閱PEP 274
uj5u.com熱心網友回復:
您可以使用 python Dictionary(get) 的內置方法
{key:value for key,value in thisdict.items() if thisdict.get(key)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358751.html
下一篇:將python字典鍵乘以一個常量
