No value in python dictionary

Is it possible to check the absence of a value in a 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 

Printing three good results after running a piece of code.

 good good good 

Required: if the value is None, and not printing good for the dict a and c keys.

+6
source share
2 answers

Your no values ​​are actually strings in the dictionary.

You can check "No" or use the actual None python 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 need to use your current dictionary, just change your check to find 'None'

additionally dict is a type built in python, so it would be nice to name dict variables

+18
source

Define a dictionary with

 d = {'a': None} 

but not

 d = {'a': 'None'} 

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

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

Source: https://habr.com/ru/post/926053/


All Articles