How to test if a key in a dictionary exists?

mensanator at aol.com mensanator at aol.com
Sat Mar 10 21:08:19 EST 2007


On Mar 10, 3:17?pm, "Frank" <super... 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!

I often build histograms using dictionaries.

if hist.has_key(outcome):
    hist[outcome] += 1  # if key already exists, increment
else:
    hist[outcome] = 1   # else create a new key


>
> Frank





More information about the Python-list mailing list