Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
Sometimes in coding we see a python code like below:

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