Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if dictionary key has empty value

I have the following dictionary

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

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

  1. it will not contain keys with empty strings.
  2. it will not contain those keys that I dont want to include.

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} 

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}

the resulting dict should look like the one below:

new = {"name":"yass"}
like image 343
hjelpmig Avatar asked May 22 '13 13:05

hjelpmig


1 Answers

This is a white list version:

>>> 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 version:

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

Both are essentially the same expect one has not in the other in. If you version of python supports it you can do:

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

and

>>> dict2 = {k: v for k, v in dict1.items() if v and k not in blacklist}
like image 113
HennyH Avatar answered Sep 21 '22 13:09

HennyH