get() method for python dictionary

get() method is useful when accessing key-value pair from a dictionary. It returns a pre-defined value (-1 in the example below) if key is not present in dictionary, else it returns the value associated with key.

char = {1:'c',2:'h'}

print(char.get(1,-1))
print(char.get(3,-1))

======================OUTPUT======================
‘c’
-1
==================================================

 

get() method can be used to create a counter like shown below;

empty_dict = {}
for e in "Let's Talk about `get()` method":
    empty_dict[e] = empty_dict.get(e, 0) + 1

print(empty_dict)

======================OUTPUT======================

{‘ ‘: 4,
“‘”: 1,
‘(‘: 1,
‘)’: 1,
‘L’: 1,
‘T’: 1,
‘`’: 2,
‘a’: 2,
‘b’: 1,
‘d’: 1,
‘e’: 3,
‘g’: 1,
‘h’: 1,
‘k’: 1,
‘l’: 1,
‘m’: 1,
‘o’: 2,
‘s’: 1,
‘t’: 4,
‘u’: 1}

==================================================

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s