![Dictionaries have a get() methodology Dictionaries have a get() methodology](https://techtoguide.com/wp-content/uploads/2023/10/Using-Python-to-Post-Stories-on-Instagram.jpg)
[ad_1]
Okay right here we’re with one more put up. Nevertheless this put up goes to be brief as on this put up i’m going to show you a small, easy and really helpful trick. Have you ever ever tried to entry a worth from a dictionary and bought an exception that there isn’t a worth mapped to that key? Like this:
>>> dict = {'key1':2,'key2':3}
>>> dict['key1']
2
>>> dict['key3']
Traceback (most up-to-date name final):
File "", line 1, in
dict['key3']
KeyError: 'key3'
Typically you do not need something like this as a result of this error can break your entire program and make it ineffective till you repair this challenge. Is there any means by way of which we will see if a secret’s current in a dictionary or not and if it isn’t current then get a default worth in it’s place? the possibilities are that you simply don’t know of any such methodology. Okay so right here’s the trick. Simply study the code under and i’ll clarify it later.
>>> dict = {'key1':2,'key2':3}
>>> dict['key1']
2
>>> a = dict.get('key3', 0)
>>> print a
0
So what is going on above? We’re nonetheless accessing the identical key however the place has the exception gone? Let me introduce you to get()
methodology which is accessible with a dictionary. What this methodology does is that it means that you can specify a default worth which is returned in case the hot button is not current within the dictionary.
In our case there isn’t a key3
in our dict however once we are utilizing the get()
methodology we’re specifying the default worth which ought to be returned in case if key3 just isn’t current and the default worth which i’ve set is 0. The syntax of the get methodology is:
dict.get('anykey','the default worth to return if the hot button is not current')
Nevertheless if we don’t set a default worth then this returns None
if the hot button is not current. I hope it’s sufficient for you guys nevertheless if you wish to additional discover this get()
methodology then google is your good friend.
Do share your views within the feedback under.
[ad_2]