In my Ruby application I have a hash table:
c = {:sample => 1,:another => 2}
I can handle the table like this:
[c[:sample].nil? , c[:another].nil? ,c[:not_in_list].nil?]
I'm trying to do the same thing in Python. I created a new dictionary:
c = {"sample":1, "another":2}
I couldn't handle the nil value exception for:
c["not-in-dictionary"]
I tried this:
c[:not_in_dictionery] is not None
and it is returning an exception instead of False.
How do I handle this?
In your particular case, you should probably do this instead of comparing with
None
:If you were literally using this code, it will not work:
Python doesn't have special
:
keywords for dictionary keys; ordinary strings are used instead.The ordinary behaviour in Python is to raise an exception when you request a missing key, and let you handle the exception.
If you want to get
None
if a value is missing you can use thedict
's.get
method to return a value (None
by default) if the key is missing.To just check if a key has a value in a
dict
, use thein
ornot in
keywords.Python includes a module that allows you to define dictionaries that return a default value instead of an error when used normally:
collections.defaultdict
. You could use it like this:Notice the confusing behaviour with
in
. When you look up a key for the first time, it adds it pointing to the default value, so it's now considered to bein
thedict
.