Using dict.get()

dict.get() is used to get the value of an item in a given dictionary using its key (see W3Schools for further reference). Why do we use e this method? We can access the item value just by calling its key directly, can't we? (e.g. dict[key])

I think the main advantage of this method is we can actually check whether or not a key exists in the given dictionary without having the hassle of getting an error returned if the key does not exist.

How come?

dict.get() accepts two parameters: the key itself and ... the value  (optional). The value will return a specified value if the key we look for does not exist in the dictionary.

Example:

Suppose we have a dictionary, namely d, as follows:

d = {'a': 1, 'b':2, 'c':3}

Suppose we would like to get the value of an item with key = 'z'. 

d['z'] will raise an error due to the fact that there is no item in the dictionary d whose key is 'z'. 

Now, if we apply dict.get() as follows: 

dict.get('z', '?')

By calling dict.get() with specified value '?', it will return '?' when we try to obtain an item with key='z'. 

Simple and clean. I personally think this method is suitable for particular purposes such as data pre-processing.


Komentar

Postingan populer dari blog ini

Fakta dan Cerita di Balik Lagu-lagu OASIS

Bandung

Sandwich Generation My Ass