PuppyCoding

Friendly Python & AI tutorials for beginner & intermediate programmers.


Avoid Key Errors with Python’s get() Function

A friendly monster holding some keys.

Have you ever tried to access a dictionary value and the key you expect is not there? (I’m looking at you, ChatGPT 😉) That’s where get() saves the day. It’s a way of avoiding a KeyError and here’s how to use it.

Instead of accessing a property in a dictionary directly, you can use the get() function to do the same thing safely, and you get to choose an alternative too.

The get() function will get a value from a dictionary if the key exists. If not, it either returns None, or returns a default value that you can specify. It’s like an if statement without having to write an if statement.

Here’s an example:

grades = {
    "Alice": 90,
    "Bob": 85
}

# When a key exists.
grade = grades.get("Alice")
print(grade)  # Prints 90

# When a key doesn't exist.
grade = grades.get("Charlie")
print(grade)  # Prints "None"

# When a key doesn't exist and there's a default value.
grade = grades.get("Charlie", 0)
print(grade)  # Prints 0

In this example, we have a grades dictionary. When we use get() to retrieve the grade for “Alice”, it returns 90 because “Alice” is present in the dictionary. But when we look up the grade for “Charlie” (who’s not in the dictionary), it returns “None”, or a default value that we provide – in this case, 0.

Even with GPT function calling, I find there are times when a key doesn’t exist in the API’s JSON object response. In those cases, the get() function is helpful by giving us a fallback without having to deal with a KeyError.

Of course, you should still use error handling but it’s great to have this alternative.




One response to “Avoid Key Errors with Python’s get() Function”

  1. […] For dealing with KeyError in particular, I recommend using Python’s get() function to access object or dictionary keys, instead of using square […]

    Like

Leave a comment