如何在不触发KeyError的情况下从Python字典中提取项目?在Perl中,我会这样做:
$x = $hash{blah} || 'default'
Run Code Online (Sandbox Code Playgroud)
什么是等效的Python?
使用get(key, default)方法:
>>> dict().get("blah", "default")
'default'
Run Code Online (Sandbox Code Playgroud)
如果你要做很多事情,最好使用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']
Run Code Online (Sandbox Code Playgroud)