tags:

views:

128

answers:

4

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?

+8  A: 

Use the get(key, default) method:

>>> dict().get("blah", "default")
'default'
phihag
A: 
x = hash['blah'] if 'blah' in hash else 'default'
cobbal
A: 
x = hash.has_key('blah') and hash['blah'] or 'default'
jonstjohn
+7  A: 

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']
unwind