How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do:
$x = $hash{blah} || 'default'
What's the equivalent Python?
How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do:
$x = $hash{blah} || 'default'
What's the equivalent Python?
Use the get(key, default)
method:
>>> dict().get("blah", "default")
'default'
If you're going to be doing this a lot, it's better to use collections.defaultdict:
import collections
# Define a little "factory" function that just builds the default value when called.
def get_default_value():
return 'default'
# Create a defaultdict, specifying the factory that builds its default value
dict = collections.defaultdict(get_default_value)
# Now we can look up things without checking, and get 'default' if the key is unknown
x = dict['blah']