Fast Dictionary Access

Paul Rubin http
Sat Jun 27 05:58:21 EDT 2009

Thomas Lehmann <Iris-und-Thomas-Lehmann at> writes:
> <code>
> if  data.has_key(key):
>    value = data[key]
> </code>
> But this does mean (does it?) that the dictionary is searched two
> times! If so, can somebody show me how to do this in one step?

  value = data.get(key, None) 

sets value to None if the key is not in the dictionary.  You can use
some other sentinel if None might actually be a value in the
dictionary.  One way to get a unique sentinel is:

   sentinel = object()

You can also use exception handling (this is quite efficient in Python)
as Chris Rebert mentioned.

More information about the Python-list mailing list