Return None if Dictionary key is not available
Solution 1:
You can use dict.get()
value = d.get(key)
which will return None
if key is not in d
. You can also provide a different default value that will be returned instead of None
:
value = d.get(key, "empty")
Solution 2:
Wonder no more. It's built into the language.
>>> help(dict) Help on class dict in module builtins: class dict(object) | dict() -> new empty dictionary | dict(mapping) -> new dictionary initialized from a mapping object's | (key, value) pairs ... | | get(...) | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. | ...