views:

68

answers:

3

I have 2 dictionaries, and I want to check if a key is in either of the dictionaries.

I am trying:

if dic1[p.sku] is not None:

I wish there was a hasKey method, anyhow.

I am getting an error if the key isn't found, why is that?

+7  A: 

Use the in operator:

if p.sku in dic1:
    ...

(Incidentally, you can also use the has_key method, but the use of in is preferred.)

Michael Williamson
You can also do this for lists, tuples, and strings.
Zonda333
`has_key` is deprecated
gnibbler
A: 

They do:

if dic1.has_key(p.sku):
banx
`has_key` is deprecated
gnibbler
@gnibbler: The question didn't say what version of python is used, so the answer was based on the typical widely used version 2.6.
banx
@banx, deprecated means it is still there for backward compatibility, but you shouldn't usually use it for new code. `in` has been the preferred way for many years now
gnibbler
A: 

if dic1.get(p.sku) is None: is the exact equivalent of what you're trying except for no KeyError -- since get returns None if the key is absent or a None has explicitly been stored as the corresponding value, which can be useful as a way to "logically delete" a key without actually altering the set of keys (you can't alter the set of keys if you're looping on the dict, nor is it thread-safe to do so without a lock or the like, etc etc, while assigning a value of None to an already-existing key is allowed in loops and threadsafe).

Unless you have this kind of requirement, if p.sku not in dic1:, as @Michael suggests, is vastly preferable on all planes (faster, more concise, more readable, and so on;-).

Alex Martelli