How to handle KeyError using get().

How to handle KeyError using get().

Clock Icon2018.07.29

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

I often use Python with AWS Lambda, but sometimes it returns a KeyError. In this post, I will illustrate how to handle KeyError errors.

KeyError occurs when you use a non-existent key.

>>> email = {
...     "user1": "[email protected]",
...     "user2": "[email protected]",
...     "user3": "[email protected]"
... }
>>>
>>> def get_email_address(user_id):
...     return "%s email = %s" % (user_id, email[user_id])
...
>>> get_email_address("user1")
'user1 email = [email protected]'
>>> get_email_address("user4")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in get_email_address
KeyError: 'user4'

How to handle

Using try-except

I believe most people would use try-except statement to catch the exception.

>>> def get_email_address(user_id):
...     try:
...             return "%s email = %s" % (user_id, email[user_id])
...     except KeyError:
...             return "%s email = None" % user_id
...
>>> get_email_address("user1")
'user1 email = [email protected]'
>>> get_email_address("user4")
'user4 email = None'

Using in operator and if statement

The in operator checks an expression and returns True if the value exists and False otherwise.

>>> def get_email_address(user_id):
...     if user_id in email:
...              return "%s email = %s" % (user_id, email[user_id])
...     else:
...             return "%s email = None" % user_id
...
>>> get_email_address("user1")
'user1 email = [email protected]'
>>> get_email_address("user4")
'user4 email = None'

Using dict.get(key[, default])

The get method returns a value if the specified key is in dict. If the specified key is not in dict, and there is a second argument, the second argument is returned. Otherwise, the default is to return None if there is no value.

Default

>>> def get_email_address(user_id):
...     return "%s email = %s" % (user_id, email.get(user_id))
...
>>> get_email_address("user1")
'user1 email = [email protected]'
>>> get_email_address("user4")
'user4 email = None'

Second argument

>>> def get_email_address(user_id):
...     return "%s email = %s" % (user_id, email.get(user_id, 'not exist'))
...
>>> get_email_address("user1")
'user1 email = [email protected]'
>>> get_email_address("user4")
'user4 email = not exist'

It is a best practice to use the get() method rather than the previous Using in operator and if statement method because using "in operator and if statement" queries dict twice while get() is more efficient with one query.

Conclusion

I have illustrated how to handle KeyError in this blog. I hope it will be helpful when the same error occurs for you.

References

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.