Fast Dictionary Access

Scott David Daniels Scott.Daniels at Acm.Org
Sat Jun 27 16:01:01 EDT 2009

Thomas Lehmann wrote:
> In C++, programming STL you will use the insert method which always
> provides a position and a flag which indicates whether the position
> results from a new insertion or an exisiting element. Idea is to have
> one search only.
> <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?

To get almost the same result (assuming value is already loaded):

      value = data.get(key, value)

Otherwise, as others have said:

      if key in data:
          value = data[key]

The form:

         value = data[key]
     except KeyError:

works, but is not terribly efficient unless failures are rare.
And this is a micro-optimization, measure before changing your
program structure away from the clearest code you can write.

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list