Return None if Dictionary key is not available

Spyros picture Spyros · May 25, 2011 · Viewed 373.2k times · Source

I need a way to get a dictionary value if its key exists, or simply return None, if it does not.

However, Python raises a KeyError exception if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None if the key does not exist?

Answer

Tim Pietzcker picture Tim Pietzcker · May 25, 2011

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