检查字典键是否有空值 [英] check if dictionary key has empty value

查看:128
本文介绍了检查字典键是否有空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字典

dict1 ={"city":"","name":"yass","region":"","zipcode":"",
       "phone":"","address":"","tehsil":"", "planet":"mars"}

我正在尝试创建一个基于dict1的新词典,但是,

I am trying to create a new dictionary that will be based on dict1 but,


  1. 它不会包含空字符串的键。

  2. 它不会包含我不想包括的那些键。 >
  1. it will not contain keys with empty strings.
  2. it will not contain those keys that I dont want to include.

我已经能够满足要求2但遇到要求1的问题。这是我的代码如何。

i have been able to fulfill the requirement 2 but getting problem with requirement 1. Here is what my code looks like.

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
我也尝试过以下,但没有如果k不在黑名单中,而且dict1 [k]是在...中,则对于k中的k,在dict1中,

this gives me the dictionary without the keys: "tehsil", "planet" I have also tried the following but it didnt worked.

new = {k:dict1[k] for k in dict1 if k not in blacklist and dict1[k] is not None}

所得到的dict应如下所示:

the resulting dict should look like the one below:

new = {"name":"yass"}


推荐答案

这将是最快的方法(使用set 区别):

This would have to be the fastest way to do it (using 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 交集):

White list version (using set intersection):

>>> whitelist = {'city', 'name', 'region', 'zipcode', 'phone', 'address'}
>>> {k: dict1[k] for k in dict1.viewkeys() & whitelist if dict1[k]}
{'name': 'yass'}

这篇关于检查字典键是否有空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆