Sometimes in coding we see a python code like below:
The above code is error prone.
In case users variable does not contain
That curly braces will do the job in case extra_info field is not present in users variable.
#python #dictionary #get #keyError
users.get('extra_info').get('browser')
The above code is error prone.
get
method is usually used to prevent throwing error when accessing a non-existent key. For instance if we try to access extra_info that does not exist, the code below will throw KeyError
exception:> users['extra_info']
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 'extra_info'
In case users variable does not contain
extra_info
, None will be returned and the get will be applied on None value, to prevent such error you need to return {} as default value:users.get('extra_info', {}).get('browser')
That curly braces will do the job in case extra_info field is not present in users variable.
#python #dictionary #get #keyError