How to test if a key in a dictionary exists?

Jeff McNeil jeff at jmcneil.net
Sat Mar 10 16:26:12 EST 2007


Sure, you can use "if key in dict" to test for membership:


Python 2.3.5 (#1, Jan 13 2006, 20:13:11)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> exampledict = {"a" : 1, "b" : 2}
>>> "a" in exampledict
True
>>> "q" in exampledict
False
>>>

Alternatively, "exampledict.has_key("a")" is also valid.

See:

http://docs.python.org/tut/node7.html#SECTION007500000000000000000

-Jeff

On 10 Mar 2007 13:17:11 -0800, Frank <supervau at gmail.com> wrote:
> Hi,
>
> does anyone know how one can test if, e.g., a dictionary 'name' has a
> key called 'name_key'?
>
> 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'
>
>
> But certainly not efficient. I would expect there is something like:
>
> name.is_key(name_key)
>
> I appreciate your help!
>
> Frank
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list