如何在不触发KeyError的情况下从Python字典中提取项目?在Perl中,我会这样做:
$x = $hash{blah} || 'default'
什么是等效的Python?
答案 0 :(得分:9)
使用get(key, default)
方法:
>>> dict().get("blah", "default")
'default'
答案 1 :(得分:7)
如果你要做很多事情,最好使用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']
答案 2 :(得分:1)
x = hash['blah'] if 'blah' in hash else 'default'
答案 3 :(得分:0)
x = hash.has_key('blah') and hash['blah'] or 'default'