Rodrigo πŸπŸš€ Profile picture
Oct 7, 2021 β€’ 12 tweets β€’ 4 min read β€’ Read on X
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!

β€’ β€’ β€’

Missing some Tweet in this thread? You can try to force a refresh
γ€€

Keep Current with Rodrigo πŸπŸš€

Rodrigo πŸπŸš€ Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @mathsppblog

May 18, 2023
I know `print` is the first Python 🐍 function you learned! πŸš€

And yet, you don't know this about `print` πŸ‘‡ Image
What you know for sure is that `print` will take an object and it will print it on the screen.

That's the basic functionality it provides: Image
Maybe you don't know that `print` can actually print multiple things!

If you pass multiple arguments, they all get printed: Image
Read 11 tweets
May 17, 2023
I'll tell you the story of a person that had the wrong name…

And how to prevent that in Python 🐍 with properties πŸš€.

πŸ‘‡ Image
John Doe was a regular guy and when he was born, he was inserted into the government's database of people.

They created a new `Person` and added John's details: Image
John never liked his name Doe, though.

So Joe decided to change his name to Smith.

And so he did.

He updated his last name, but the government `Person` STILL had the wrong name! Image
Read 10 tweets
May 14, 2023
Opening a file to read/write is a common task in Python 🐍.

Here is how to do it right! πŸš€

πŸ‘‡ Image
Python has a built-in `open` that takes a file path and opens that file.

Then, you have to specify whether you want to open the file to read, write, or append.

But this isn't half of the story! Image
The default behaviour is to open the file to read/write text.

This works well with TXT or CSV files, for instance.

If you need to open a file to read its binary contents, you can add a `"b"` to the mode: Image
Read 6 tweets
May 13, 2023
The Python 🐍 built-in `round` is great. πŸš€

Here are some tips on it. πŸ‘‡ Image
The purpose of `round` is to… round numbers!

It rounds numbers to the closest integer.

These are some simple examples: Image
However, if the number ends in `.5`, what is the closest integer?

In that case, `round` will choose the even number.

This means it may round up or down πŸ€ͺ

(In school, I was taught to round `.5` up… 🀷) Image
Read 6 tweets
May 12, 2023
Error handling in Python 🐍 made simple. πŸš€

πŸ‘‡ Image
The keyword `try` is used before code that might fail.

So, if you know something can raise an error, you can write it inside a `try` statement: Image
Now that the code is inside a `try` statement, you need to tell Python what error you want to handle, and how.

That's when the keyword `except` comes in! Image
Read 7 tweets
May 11, 2023
Every Python 🐍 programmer uses the ICPO rule. πŸš€

Even if you don't know what it is.

Let me tell you what the ICPO rule is and what it does πŸ‘‡ Image
The ICPO rule is what determines how attribute and method lookup work.

More precisely, it is the ICPO rule that tells Python where to look for attributes and methods in your objects.

This is relevant because everything in Python is an object.
Because everything is an object, that means Python is incredibly consistent in some things.

For example, did you know that everything has a type? Image
Read 13 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us!

:(