I have code that works but I'm wondering if there is a more pythonic way to do this. I have a dictionary and I want to see if:
- a key exists
- that value isn't None (NULL from SQL in this case)
- that value isn't simply quote quote (blank?)
- that value doesn't solely consist of spaces
So in my code the keys of "a", "b", and "c" would succeed, which is correct.
import re
mydict = {
"a":"alpha",
"b":0,
"c":False,
"d":None,
"e":"",
"g":" ",
}
#a,b,c should succeed
for k in mydict.keys():
if k in mydict and mydict[k] is not None and not re.search("^\s*$", str(mydict[k])):
print(k)
else:
print("I am incomplete and sad")
What I have above works, but that seems like an awfully long set of conditions. Maybe this simply is the right solution but I'm wondering if there is a more pythonic "exists and has stuff" or better way to do this?
UPDATE Thank you all for wonderful answers and thoughtful comments. With some of the points and tips, I've updated the question a little bit as there some conditions I didn't have which should also succeed. I have also changed the example to a loop (just easier to test right?).
if mydict.get("a", "").strip():
?None
and""
are both falsey. – Promptitudemydict['a'] is None
, asNone
doesn't have astrip
method. – Wallah"a" in mydict
without having to callmydict.keys()
– Lessen""
so you don't have to consider them separately later.) – Wallah