user1636419
user1636419

Reputation: 239

None value in python dictionary

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.

Upvotes: 20

Views: 134080

Answers (4)

Kush
Kush

Reputation: 61

Instead of using "if value is None" you can simply use

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

for k, v in d.items():
    if v: 
        print("good")
    else: 
        print("bad")

"if v" will be True if there is any kind of value except None. Hence you don't have to explicitly use None keyword in if condition (if v is None).

Result:
bad
good
bad
good

In last case the value for key 'd' is 'None' - as a string not python value None

Upvotes: 1

Ulrik Larsen
Ulrik Larsen

Reputation: 139

def none_in_dict(d):
    for _, value in d.items():
        if value is None:
            return True
    return False

And the use is:

if none_in_dict(my_dict):
    logger.error(my_err_msg)

Upvotes: 1

dm03514
dm03514

Reputation: 55922

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

Upvotes: 39

Dr. Jan-Philip Gehrcke
Dr. Jan-Philip Gehrcke

Reputation: 35761

Define your dictionary with

d = {'a': None}

rather than

d = {'a': 'None'}

In the latter case, 'None' is just a string, not Python's None type. Also, test for None with the identity operator is:

for key, value in d.iteritems():
    if value is None:
        print "None found!" 

Upvotes: 10

Related Questions