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.
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.
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.
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.
# 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!
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
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!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With