Way for see if dict has a key

B

Bruno Desthuilliers

Georg said:
Bruno said:
looping said:
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().
 
A

Alex Martelli

Fredrik Lundh said:
new syntax (2.3 and later).

Fine with Python 2.2 as well, actually -- so, "new" only in an
_extremely_ loose sense of the word:).


Alex
 
E

Eric Deveaud

Bruno said:
Seems that if "key in dict" do a simple linear search, it depends on the
number of keys in dict (and the position of the searched key etc...).

And if I'm missing the point and you it and you know why, it would be
simple to explain than to answer my question with another question.


maybee we can imagine that key in dict
just perform
try:
dict[key]
return True
except KeyError:
return False

If I understand correctly, it will be time constant no ??
just the needed time to compute the hash for the key

Eric
 
G

Georg Brandl

Bruno said:
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().

You're right, and I would write that with explicit None too.
Just wanted to continue the shortening ;)

Georg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top