Click here to Skip to main content
15,886,740 members
Articles / Programming Languages / Python2.7
Tip/Trick

Python Dictionary's get() method

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
16 Sep 2014CPOL 8.6K   2  
Python dictionary supports a get() method that helps to look up a key and perform assignment operation in one line of code!

Introduction

Generally, while checking for a key in a dictionary, we tend to use an if and then use the same key to assign a value to it, thus using 4 lines of code and also looking up the key twice, once for the if loop and then for the assignment operation.

Example:

C#
if 'owner' in roledict:
    owner = roledict['owner']
else:
    owner = admin

The same functionality can be achieved by using the dictionary's get method as:

C#
owner = roledict.get('owner', admin)

The get method of dictionary takes a second optional argument which is assigned if the key (first argument) is not found in the dictionary.

Points of Interest

Using the get method not only reduces lines of code, but also makes the code more readable.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Mindfire Solutions
India India
Writing python code @ Mindfire Solutions, Noida.

Comments and Discussions

 
-- There are no messages in this forum --