Friday, June 9, 2023
HomePythonDictionaries have a get() technique

Dictionaries have a get() technique

Okay right here we’re with yet one more publish. Nonetheless this publish goes to be quick as on this publish i’m going to show you a small, easy and really helpful trick. Have you ever ever tried to entry a price from a dictionary and received an exception that there is no such thing as a worth mapped to that key? Like this:

>>> dict = {'key1':2,'key2':3}
>>> dict['key1']
>>> dict['key3']

Traceback (most up-to-date name final):
  File "", line 1, in 
KeyError: 'key3'

Typically you do not need something like this as a result of this error can break your complete program and make it ineffective till you repair this situation. Is there any means by way of which we are able to see if a secret is current in a dictionary or not and if it’s not current then get a default worth in it’s place? the possibilities are that you simply don’t know of any such technique. 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']
>>> a = dict.get('key3', 0)
>>> print a

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() technique which is obtainable with a dictionary. What this technique does is that it means that you can specify a default worth which is returned in case the secret’s not current within the dictionary.

In our case there is no such thing as a key3 in our dict however once we are utilizing the get() technique we’re specifying the default worth which must be returned in case if key3 will not be current and the default worth which i’ve set is 0. The syntax of the get technique is:

dict.get('anykey','the default worth to return if the secret's not current')

Nonetheless if we don’t set a default worth then this returns None if the secret’s not current. I hope it’s sufficient for you guys nonetheless if you wish to additional discover this get() technique then google is your good friend.

Do share your views within the feedback under.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments