检查字典键是否为空值

时间:2013-05-22 13:59:46

标签: python dictionary

我有以下字典

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

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

  1. 它不包含空字符串的键。
  2. 它不会包含我不想包含的那些键。
  3. 我已经能够满足要求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"}
    

5 个答案:

答案 0 :(得分:4)

这是一个白名单版本:

>>> dict1 ={"city":"","name":"yass","region":"","zipcode":"",
       "phone":"","address":"","tehsil":"", "planet":"mars"}
>>> whitelist = ["city","name","planet"]
>>> dict2 = dict( (k,v) for k, v in dict1.items() if v and k in whitelist )
>>> dict2
{'planet': 'mars', 'name': 'yass'}

黑名单版本:

>>> blacklist = set(("planet","tehsil"))
>>> dict2 = dict( (k,v) for k, v in dict1.items() if v and k not in blacklist )
>>> dict2
{'name': 'yass'}

两者基本相同,期望not in另一个in。如果你的python版本支持它,你可以这样做:

>>> dict2 = {k: v for k, v in dict1.items() if v and k in whitelist}

>>> dict2 = {k: v for k, v in dict1.items() if v and k not in blacklist}

答案 1 :(得分:2)

这必须是最快的方法(使用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'}

答案 2 :(得分:1)

你走在正确的轨道上。考虑:

Python 2.7.3 (default, Apr 24 2012, 00:00:54) 
[GCC 4.7.0 20120414 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dict1 ={"city":"","name":"yass","region":"","zipcode":"",
...    "phone":"","address":"","tehsil":"", "planet":"mars"}
>>> 
>>> def isgood(undesired, key, val): return key not in undesired and key and val
... 
>>> dict([x for x in dict1.items() if isgood(["planet", "tehsil"], *x)])
{'name': 'yass'}

答案 3 :(得分:1)

只需测试dict1[k]的真值(而不是is None。)。

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

答案 4 :(得分:1)

使用is not None测试该值是否为空字符串。

空字符串的计算结果为False,而任何非空字符串的计算结果为True。因此,您可以直接测试它,只需从表达式中删除is not None

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