Why to use get(key) instead of [key] for Python Dictionary?

Accessing value from a dictionary using square brackets will raise an exception if there is no value mapped to that key, here is an example
>>> dict = {'key1':1,'key2':2}
>>> dict['key1']
1
>>> dict['key3']

Traceback (most recent call last):
  File "", line 1, in 
    dict['key3']
KeyError: 'key3'
On the other hand, 'get' will return the default value if there is no value mapped to that key, the default value is 'None' by default
>>> dict = {'key1':1,'key2':2}
>>> dict['key1']
1
>>> a = dict.get('key3)
>>> print a
0
To set a custom default value
>>> a = dict.get('key3', 'MyCustomValue')

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Difference between Validations, Callbacks and Observers