Member-only story

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…