65.9K
CodeProject is changing. Read more.
Home

Python Dictionary's get() method

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Sep 16, 2014

CPOL
viewsIcon

8761

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:

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

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

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.