Re: Way for see if dict has a key



Fredrik Lundh wrote:
"André" wrote:


Perhaps Bruno meant this:

try:
... my_dict[key] ...
except:
...

when we expect that the key will most often be in my_dict so that
exception will be raised rarely, otherwise use


on my machine, "key in dict" is about twice as fast as the full try/getitem con-
struct when the key is present in the dict,

Doesn't it depends on the number of keys in the dict ?

so that's not a very good optimization.

FWIW, I personaly didn't meant to present it as an optimisation - just
as one more possible way to test the existence of a given key...

now, if the OP had been interested in the associated value, things might have
been a bit different.

</F>





--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb@xxxxxxxxxxx'.split('@')])"
.



Relevant Pages

  • Unexpected behavior of read only attributes and super
    ... I have been playing around with a subclass of dict wrt a recipe for setting dict items using attribute syntax. ... The dict class has some read only attributes that generate an exception if I try to assign a value to them. ...
    (comp.lang.python)
  • Re: default value for list access?
    ... > before I access it (or use exception). ... > If I use the getItem function in my previous email, ... > def df(a, idx, default): ... For dict something like this: ...
    (comp.lang.python)
  • Re: Exception not raised
    ... on a piece of code doesn't raise a KeyError on a dict (that ... Other strange thing is that other exceptions are ... so python see that exception inside the ...
    (comp.lang.python)
  • Re: Why are there no ordered dictionaries?
    ... >> Fredrik Lundh wrote: ... we don't need types other than string in a DBMS ... The dict() in my example doesn't convert be- ... > There's no parsing involved, ...
    (comp.lang.python)
  • Re: Counter Class -- Bag/Multiset
    ... what's the rationale of allowing negative values too? ... The dict values can be anything, but only ints make sense in the ... Since it is a dict subclass, we really have no control of the ... some kind of exception for attempts to set a negative value (i.e. c ...
    (comp.lang.python)