(Originally published on prahladyeri.github.io)
There is an increasing trend towards using the dict.get()
method in Python, its very widely used in many tutorials and examples too. Condsider the below example for instance:
>>> dd = {'a': 1}
>>> dd.get('a')
1
This simple dictionary dd has only one key ('a') and its corresponding value is 1. The proper way of accessing this key is to refer it as dd['a']
but you need to be sure that the dictionary has that key otherwise it'll throw an error! Hence, as a shortcut way, programmers have started using dd.get()
method instead. This method simply returns the key value if its present and None
if there is no such key in the dictionary.
Seems good enough, right? Well, don't fall into that trap so soon! In the real world, you'll come across a situation sooner or later when you'll have to handle a dictionary key who's value is None
! What will you do then? Consider this example:
>>> dd = {'a': None}
>>> dd.get('a')
In this case, you'll never know whether a key was present in the dictionary or one was there and its value was None
. Knowing the difference could be crucial in some situations and not doing so might cause subtle bugs in your program which will be very hard to trace later. The best habit to access a dictionary is this:
>>> if 'a' in dd:
>>> x = dd['a'] # do whatever
>>> else:
>>> pass # handle this
Or you can even simply refer its key directly if you are sure that the key exists:
>>> x = dd['a'] # do whatever
Similarly, there are two different ways to remove an item from dictionary but there is nothing wrong in using either of them (except of course that you need to be sure that the key is present and use an exception handler if you aren't):
>>> dd.pop('a')
>>> del dd['a']
Top comments (5)
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 -
It is nicer to write
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)
Letting Python raise an exception and catch it is also valid :)
Python embraces the concepts of EAFP (easier to ask forgiveness than permission) over LYBL (look before you leap):
EAFP
LYBL
EAFP is also safer in multithreaded environments (though you probably wouldn't directly access a plain dictionary anyway, but that's another story).
Exceptions in Python are quite cheap, even though sometimes are used as a control statement like this 👀
What's the problem with doing this?
Here is a more compact version after removing the extra else and putting the condition inline:
I think never in the title is too exaggeration