Skip to main content
cross-link directly related question
Source Link
Karl Knechtel
  • 61.4k
  • 14
  • 133
  • 193

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?


See also: Why dict.get(key) instead of dict[key]?

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?

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?


See also: Why dict.get(key) instead of dict[key]?

the question and answers are valid for default values other than None
Source Link
mkrieger1
  • 24.2k
  • 7
  • 68
  • 84

Return Nonea default value if Dictionarya dictionary key is not available

improved formatting
Source Link
Loading
Source Link
Spyros
  • 48.9k
  • 26
  • 94
  • 134
Loading