Python: What is .get() and Why Should I Use It?

Learn how the .get() method can improve your code and make your life easier!

Python: What is .get() and Why Should I Use It?

Ideally we’d all love to code in a perfect environment—variables always exist, data types are always correct, users never misspell or submit crazy inputs… unfortunately we exist in reality and if you don’t plan on bad data you’re going to get burned.

For this reason I’d developed a habit of making sure variables exist and that they are not null. So a simple for loop will have this type of a nesting around it:if "skills" in user and isinstance(user['skills'],list):
  for skill in user['skills']:
     # do stuff

For those more comfortable in JavaScript processing JSON data it would be something along the lines of:if(user.hasOwnProperty("skills") && Array.isArray(user.skills) {
  for(var i=0; i<user.skills.length; i++) {
     // do stuff}}

This gets really old really fast and I’m here to tell you there’s a better way.

What is the .get() Method?

Part of the dictionary class, the .get() method will retrieve a specified term from the dictionary. What happens if the term does not exist? It will return None or a value of your choosing when specifying a second argument.user = {
  "first_name": "Terra",
  "last_name": "Branford"}
print(user.get("first_name")) # Terra
print(user.get("middle_name")) # None
print(user.get("middle_name", "")) # ""

Why Should I Use It?

What is great about the .get() method is that you will not hit KeyError exceptions because a value is always returned from the method. Therefore, we don’t need to check if term exists before invoking it and can consolidate our previous check into a single expression:if isinstance(user.get("skills"),list):
  for skill in user['skills']:
     # do stuff


What are your favorite uses of .get()? Are you likely to add this to your code? Clap up the article if you found it helpful and leave any questions or comments below.

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe