Return None if Dictionary key is not available Return None if Dictionary key is not available python python

Return None if Dictionary key is not available


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")


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.     |      ...


Use dict.get

Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.