Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Python2.7

Python Dictionary's get() method

5.00/5 (4 votes)
16 Sep 2014CPOL 8.8K  
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)