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,
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"}
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With