How to test if a key in a dictionary exists?

Bjoern Schliessmann usenet-mail-0306.20.chr0n0ss at spamgourmet.com
Sat Mar 10 20:39:14 EST 2007


Frank wrote:

> does anyone know how one can test if, e.g., a dictionary 'name'
> has a key called 'name_key'?

Yes. It's already posted; next time have a look at the concise
library reference:

http://docs.python.org/lib/typesmapping.html
 
> This would be possible:
> 
> keys_of_names = names.keys()
> L = len(keys_of_names)
> 
> for i in range(L):
> if keys_of_names[i] == name_key:
> print 'found'

Coming in from Java? 8)

Iterating through something using len(X) is quite rare in Python. 

If we had no simple "key in dict" test, I'd write the above as:

for key in names.keys():
    if key == name_key:
        print "found"
        break
else:
    print "not found"

(It would even suffice to write "for key in names".)
 
Regards,


Björn

-- 
BOFH excuse #331:

those damn raccoons!




More information about the Python-list mailing list