Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if dictionary key exists, is not None and isn't blank

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?).

like image 943
sniperd Avatar asked May 03 '18 13:05

sniperd


1 Answers

Try to fetch the value and store it in a variable, then use object "truthyness" to go further on with the value

v = mydict.get("a")
if v and v.strip():
  • if "a" is not in the dict, get returns None and fails the first condition
  • if "a" is in the dict but yields None or empty string, test fails, if "a" yields a blank string, strip() returns falsy string and it fails too.

let's test this:

for k in "abcde":
    v = mydict.get(k)
    if v and v.strip():
        print(k,"I am here and have stuff")
    else:
        print(k,"I am incomplete and sad")

results:

a I am here and have stuff
b I am incomplete and sad    # key isn't in dict
c I am incomplete and sad    # c is None
d I am incomplete and sad    # d is empty string
e I am incomplete and sad    # e is only blanks

if your values can contain False, 0 or other "falsy" non-strings, you'll have to test for string, in that case replace:

if v and v.strip():

by

if v is not None and (not isinstance(v,str) or v.strip()):

so condition matches if not None and either not a string (everything matches) or if a string, the string isn't blank.

like image 163
Jean-François Fabre Avatar answered Sep 28 '22 04:09

Jean-François Fabre