Re: Way for see if dict has a key



Georg Brandl wrote:
Bruno Desthuilliers wrote:

looping wrote:

Michele Petrazzo wrote:

Bruno Desthuilliers wrote:

but what the better


Depends on the context.


If know only one context: see if the key are into the dict... What
other
context do you know?


Why do you want to do that ?

if key in dict:
value = dict[key]
else:
value = None

could be write:


value = dict.get(key, None)


value = dict.get(key)

Yes - but :
1/ not everybody knows that dict.get() takes a second optional param.
Note that, while it happens that the default return value of dict.get()
is the same as in the above example, but it may not have been the case.

2/ Since dict.get() implicitely returns None while getattr() defaults to
raising an AttributeError unless you provide a default, I prefer to be
very explicit when using dict.get().


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



Relevant Pages

  • RE: Way for see if dict has a key
    ... On Behalf Of Georg Brandl ... Bruno Desthuilliers wrote: ... If know only one context: see if the key are into the dict... ...
    (comp.lang.python)
  • Re: Way for see if dict has a key
    ... Michele Petrazzo wrote: ... If know only one context: see if the key are into the dict... ... exception will be raised rarely, ...
    (comp.lang.python)
  • Re: Way for see if dict has a key
    ... looping wrote: ... If know only one context: see if the key are into the dict... ...
    (comp.lang.python)
  • Re: Way for see if dict has a key
    ... Michele Petrazzo wrote: ... what the preferred way for see if the dict has a key? ... Depends on the context. ...
    (comp.lang.python)
  • Re: Way for see if dict has a key
    ... Michele Petrazzo wrote: ... If know only one context: see if the key are into the dict... ... except KeyError: ...
    (comp.lang.python)