Как вытащить элемент из словаря Python, не вызывая KeyError? В Perl я бы сделал:
$x = $hash{blah} || 'default'
Что такое эквивалент Python?
Используйте метод get(key, default):
get(key, default)
>>> dict().get("blah", "default") 'default'
Если вы собираетесь много заниматься этим, лучше использовать collection.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']
x = hash['blah'] if 'blah' in hash else 'default'
x = hash.has_key('blah') and hash['blah'] or 'default'