我有以下字典
dict1 ={"city":"","name":"yass","region":"","zipcode":"",
"phone":"","address":"","tehsil":"", "planet":"mars"}
我正在尝试创建一个基于 dict1 的新字典,但是,
- 它不会包含带有空字符串的键。
- 它不会包含我不想包含的那些键。
我已经能够满足要求 2,但遇到要求 1 的问题。这是我的代码的样子。
dict1 ={"city":"","name":"yass","region":"","zipcode":"",
"phone":"","address":"","tehsil":"", "planet":"mars"}
blacklist = set(("planet","tehsil"))
new = {k:dict1[k] for k in dict1 if k not in blacklist}
这给了我没有键的字典:“tehsil”,“planet” 我也尝试了以下但没有奏效。
new = {k:dict1[k] for k in dict1 if k not in blacklist and dict1[k] is not None}
生成的 dict 应如下所示:
new = {"name":"yass"}