Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 329
user1636419 Avatar asked Sep 23 '12 16:09

user1636419


People also ask

Can a dictionary value be None in Python?

The not operator is used to inverse the result to check for any of None value. This task can also be performed using the in operator and values function. We just check for None in all the values extracted using the values function and check for existence using the in operator.

What is the value of None in Python?

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.

Is None the same as null in Python?

Instead of null, there's None keyword used in Python. so there is no comparison between Python None vs null. In other programming languages null is often defined to be 0, but in Python used None to define null objects and variables. But None is not defined to be 0 or any other value.

How do I check if a dictionary key is empty?

# Checking if a dictionary is empty by checking its length empty_dict = {} if len(empty_dict) == 0: print('This dictionary is empty! ') else: print('This dictionary is not empty! ') # Returns: This dictionary is empty!


2 Answers

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

like image 153
dm03514 Avatar answered Oct 01 '22 03:10

dm03514


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!" 
like image 44
Dr. Jan-Philip Gehrcke Avatar answered Oct 01 '22 02:10

Dr. Jan-Philip Gehrcke