2012
04.04
04.04
The more verbose way of getting the value from a key in a dictionary in Python involves checking if the key exists first and then reading the value. Otherwise an exception would be raised.
Like so:
dict = {'key':'value'}
if dict.has_key('key'):
print dict['key']
else:
print 'no such key'
The .get() method will do all that for you:
print dict.get('key', 'no such key')
This is far more compact and expressive. Ref: Python Mapping Types – dictionary
No Comment.
Add Your Comment