KeyError
test = {}
print test['a']
When you run this sample
KeyError: 'pagename'
Exception occurs. In order to avoid this, it is necessary to check in advance whether or not the key exists by using ʻin,
has_key`, etc.
test = {}
if 'a' in test:
print test['a']
else:
print ''
The code looks like this, but in the above cases, it seems that a convenient method called get
is provided.
get(key[, default])
Quoted from Documents
If key is in the dictionary, it returns the value for key. Otherwise, it returns default. If no default is given, it defaults to None. Therefore, this method never throws a KeyError.
It seems that you can also specify the default value by specifying the second argument. Let's rewrite the above code using get
test = {}
print test.get('a')
It's very simple.
Recommended Posts