Do dictionaries have a has key method? I'm checking for 'None' and I'm having issues
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?
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.)
They do:
if dic1.has_key(p.sku):
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;-).
精彩评论