Another simple python example which is how to find out if a key exists in python

Just use "if" and "in" like in the following example

x['item1'] = 0
if 'item1' in x:
 print "True"

The above will print true

Some of the mistakes that I have seen is this will "appear" to work correctly but in fact it does not. Have a look at these examples. You can see here that it will fail because it is testing the value rather than the key.

x['item1'] = 1
if x['item1']:
 print "True"

The above will also print true

x['item1'] = 0
if x['item1']:
 print "True"

The above won't print true



Did You find this page useful?

Yes No



Last Modified: 21 February 2017

Releated Posts


2013-04-09 - Python - How to find out if a key exists in a dictionary
2012-08-14 - Python - while else statement
2012-06-30 - CPP - Creating A basic python wrapper
2012-02-22 - Python - 2d Arrays don't work.