python判断字典值为空_python – 检查字典键是否为空值

我有以下字典

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"}

最佳答案 这必须是最快的方法(使用set

difference):

>>> dict1 = {"city":"","name":"yass","region":"","zipcode":"",

"phone":"","address":"","tehsil":"", "planet":"mars"}

>>> blacklist = {"planet","tehsil"}

>>> {k: dict1[k] for k in dict1.viewkeys() - blacklist if dict1[k]}

{'name': 'yass'}

白名单版本(使用set intersection):

>>> whitelist = {'city', 'name', 'region', 'zipcode', 'phone', 'address'}

>>> {k: dict1[k] for k in dict1.viewkeys() & whitelist if dict1[k]}

{'name': 'yass'}

你可能感兴趣的:(python判断字典值为空)