Member-only story

Jonathan Hsu
2 min readOct 2, 2019

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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response