DEV Community

Discussion on: Why you should never use the dict.get() method in Python

Collapse
 
kfirstri profile image
Kfir Stri • Edited

Cool post Prahlad! I think 'never' is a bit harsh, I agree that checking if the key exists before or if you know the key will be in the dict you should access it directly.. but, the get method is useful sometimes for default values, not just to return None..

If you got some dict full with booleans for some reason, instead of writing -

if 'some_bool' in bool_dict:
   result = bool_dict['some_bool']
else:
   result = False

It is nicer to write

result = bool_dict.get('some_bool', False)

Or many other use cases where you can use the default argument to make the .get method return something other than None (maybe your program has some default config parameters, or maybe you want to set a different string.. and so on)