Rodrigo 🐍🚀 Profile picture
Take your Python 🐍 skills to the next level 🚀!

Oct 7, 2021, 12 tweets

Python 🐍 dictionaries are amazing ✨ data structures.

Do you know how to make the best use out of them?

One method you should have in your arsenal is the `.get` method.

Here's a short thread 👇🧵 about it.

A dictionary is a “mapping”: it maps keys into values.

In Python, if you have a key, you can use it inside `[]` to access the corresponding value 👇

However, ...

... if the key doesn't exist, then you get an error!

As an example, here's my attempt at getting my age from the previous dictionary, which only knew about my name 👇

So, how to try and access keys without having Python throw an error at your face..?

One thing you can do is use the `in` operator to check if the `key` exists in your dictionary 👇

Then, you'd use an `if` statement to check if you could access a given key.

Another alternative is to use exception handling to handle the `KeyError` you get 👇

However, sometimes, either alternative is too much...

The `.get` method is a “safe” way to get a dictionary's values.

You give it a key, and the `.get` method does NOT throw an error if the key isn't there 👇

Instead, it returns `None`.

However, you can change that!

The `.get` method accepts a second argument, which is the “default value”.

The default value is what `.get` returns if the key wasn't there 👇

This is a great method to know about.

Now, when do you use `.get`?

Well, I personally like to use it when I want to try and get some information that I am going to use right away.

Except, if the info isn't there, I will do nothing.

Depending on the operation that I want to do afterwards, I use `.get` with different default values.

The idea is that the “default value” should act as a “no-op”, or a “do nothing” value for the operation that I'm doing next.

Here are some examples 👇

Imagine you need to open a dictionary to fetch a list.

After doing that, you want to use a `for` loop to go over the list...

But if there's no list, you don't want to do the `for` loop...

Instead, you can use `.get` with an empty list:

Another example which might be more down-to-Earth.

Imagine you are selling a product and your Python code is now validating the sale.

You get a dictionary with information about the product and you want to check for a discount, to apply it:

Another example I use a lot is when I need to reach inside nested dictionaries, but those nested dictionaries might not be there...

Then, using `.get` with a default value of `{}` is a real life-saver!

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling