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.