What a confuse 'False'

Hi everybody!

Recently I was working with dictionary contains 0 value and string key. Little bit annoyed when I ran the code, the algorithm was not successful. What I did was checking dictionary value (which contains 0 value) with "get" method. Yeah it's returned to 0 which is read as false in python. If you use it in if-else statement, it would be passed to else. Let me explain what I did in my case below.

The code:

1
2
3
4
5
somedict = { 'first': 0, 'second': 1}  
 if somedict.get('first', False):  
   print 'Yeay somedict is read as True'  
 else:  
   print 'No! somedict is read as False'

What I got when running the code:

Finally I got an idea to fix this. I changed my if-else statement with keys() function and guess what? It's working. Here my fix for the code above.

1
2
3
4
5
somedict = { 'first': 0, 'second': 1}  
 if 'first' in somedict.keys():  
   print 'Yeay somedict is read as True'  
 else:  
   print 'No! somedict is read as False'

Comments

Popular posts from this blog

Making SublimePythonIDE Works on Windows

Another Way to Access Virtual Machine via http