HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

Return a default value if a dictionary key is not available

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
keyreturnvalueavailablenotdictionarydefault

Problem

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]?

Solution

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 (unless the dict actually contains None as the value for this key):

value = d.get(key, "empty")

Code Snippets

value = d.get(key)
value = d.get(key, "empty")

Context

Stack Overflow Q#6130768, score: 1342

Revisions (0)

No revisions yet.