Re: Way for see if dict has a key



"Michele Petrazzo" <michele.petrazzo@xxxxxxxxxxxxxx> wrote in message
news:zZ7pg.21792$zy5.445667@xxxxxxxxxxxxxxxxxxxxx
when we expect that the key will most often be in my_dict so that
exception will be raised rarely

I didn't thought this because if I think that a key aren't in a dict, I
use dict.get(key, default)


Another factor to consider is if "default" is not something simple like 0 or
None, but is an object constructed and initialized with some expensive
initialization code (like access to a database). In this case:

dict.get(key, ExpensiveObjectToCreate())

always creates the default value, and if the key does not exist, then
promptly drops it on the floor.

In such a case you'd be better off with one of the "check for existence"
patterns, which only creates the default value if you *know* you're going to
need it.

-- Paul


.



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: LinkageError and ExceptionInInitializerError
    ... exception was thrown by a class' initialization code. ... The definitive source of information about this topic would be the Java ... Virtual Machine Specification, ...
    (comp.lang.java.programmer)
  • 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: 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)