None value in python dictionary

user1636419 picture user1636419 · Sep 23, 2012 · Viewed 71.6k times · Source

Is it possible to check none value in dict

dict = {'a':'None','b':'12345','c':'None'}

My code

for k,v in d.items():
  if d[k] != None:
    print "good"
  else:
    print "Bad 

Prints three good after executing above code snippet.

good
good
good

Required:If value is None than not printing good for dict key a and c.

Answer

dm03514 picture dm03514 · Sep 23, 2012

Your none values are actually strings in your dictionary.

You can check for 'None' or use actual python None value.

d = {'a':None,'b':'12345','c':None}

for k,v in d.items(): 
  if d[k] is None:
    print "good" 
  else: 
    print "Bad"

prints "good" 2 times

Or if you Have to use your current dictionary just change your check to look for 'None'

additionally dict is a python built in type so it is a good idea not to name variables dict