python – 检查字典键是否为空值
发布时间:2020-12-20 11:27:34 所属栏目:Python 来源:网络整理
导读:我有以下字典 dict1 ={"city":"","name":"yass","region":"","zipcode":"","phone":"","address":"","tehsil":"","planet":"mars"} 我正在尝试创建一个基于dict1的新字典,但是, 它不包含空字符串的键. 它不会包含我不想包含的那些键. 我已经能够满足要求2但
我有以下字典
dict1 ={"city":"","name":"yass","region":"","zipcode":"","phone":"","address":"","tehsil":"","planet":"mars"} 我正在尝试创建一个基于dict1的新字典,但是, >它不包含空字符串的键. 我已经能够满足要求2但是遇到问题1的问题.这是我的代码的样子. dict1 ={"city":"","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":"","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'} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |