get Method in Dictionary

If we want to add an entity to a dictionary, we normally do the following:

First we check whether the dictionary contain an item with the same key as the one we are about to add. If not, we create a new item in the dictionary with that key and return the value as 0. Then we add our value to that 0. If a item already exist we add our value with the value present in the dictionary. The following code does the same:

>>> dictionary = {}

>>> for (name,salary) in data:

…     if name not in dictionary: dictionary[name] = 0

…    dictionary[name] += salary

This code can be done much more directly using ‘get’ method available for dictionary. The code looks like:

>>>  dictionary = {}

>>> for (name,salary) in data:

…   dictionary[name] = dictionary.get(name,0) + salary

What happens  here is, if ‘name’ exist in ‘dictionary’, ‘get’ will return the value ‘dictionary[name]’. If not ‘get’ will return a new entry in ‘dictionary’ with key ‘name’ and value ‘0’.


About Odol Shinu

I've completed my B Tech in Information Technology in 2010 from Government Engineering College Sreekrishnapuram Palakkad under Calicut University.

Posted on September 1, 2010, in Python. Bookmark the permalink. Leave a comment.

Leave a Reply

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

You are commenting using your 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

%d bloggers like this: