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

6 Oct
πŸ†Β Here's a mini Python 🐍 challenge.

You have an int `value` and a dictionary `my_dict`.

`my_dict` **may** contain a key `"field"`, with an int.

If `"field"` is there, add it to `value`.

How would you solve this?

Here's a short thread πŸ‘‡πŸ§΅ with a couple of solutions.
First off, this mini thread was prompted by @svpino's most recent tweet, that I include here for credit and context:

Like Santiago pointed out, there are two archetypes of solutions here.

The first one, is to check if the `"field"` is there, and then add to `value`.

Simple to understand, but with one β€œdrawback” that bothers me just a little bit... Image
Read 11 tweets
4 Oct
What's the deal with Python 🐍's pass-by-value or pass-by-reference?

How does it relate to mutable and immutable objects?

Here's a Python thread πŸ‘‡πŸ§΅ that'll make everything crystal clear and help you master Python 🐍.

Let's go πŸš€
First thing you need to realise is that Python 🐍 does not use the pass-by-value model...

But it also does not use the pass-by-reference model!

Let me see if I can explain what I mean!

What does it mean to pass by value?
In the pass-by-value model, whenever you call a function with a given argument, that argument is fully copied into the function.

This means you can change what got into your function, and you won't be able to see the changes from the outside.

This _looks_ like pass-by-value:
Read 26 tweets
2 Oct
πŸ› πŸ‘€ On the 23/09 I challenged myself to go from 2.95k followers to 4k by the end of the month 😱

That was +1.05k followers (+36%) in 7 days.

On the 1st Oct I woke up to a little over 6k followers πŸŽ‰πŸ”₯ that's INSANE!

Thanks for your support!

Here's a recap of these days πŸ‘‡πŸ§΅
First off, for reference, here is the original tweet with the public challenge:

In the original tweet I said that my strategy would be to publish a high-value thread each day.

For my challenge to be met, I had to grow β‰ˆ4% each day.

Here's a breakdown of the number of followers I woke up to each day, with the % change relative to the previous day.
Read 13 tweets
2 Oct
I love the `enumerate` Python 🐍 built-in!

I love it because your `for` loops become much more readable ✨ if you know how to use it.

Here's a thread πŸ‘‡πŸ§΅ on how `enumerate` will make your Python code so much better.

Let's go πŸš€
Python's `for` loops are amazing!

And yet, many people write too much stuff in their loops.

For example, if you just need to go through a list, you shouldn't be writing this πŸ‘‡
In Python, you can just β€œgo through lists”, you don't need to compute the range of the length of the list!

Instead of the above, you can just write this πŸ‘‡

This is better because you can read it as β€œfor each colour in the list `l`”.
Read 16 tweets
30 Sep
β€œBe consistent”, they say.

But why?

Have you ever heard of the compounding effect?

Or exponential growth?

I'll show you how all these are connected, with real-life examples πŸ‘‡πŸ§΅ Image
I'll let you in on a little secret: I have a personal goal on Twitter.

The goal is to grow by 1% every day.

That's just that.

Every day, I want my follower count to increase by 1%

If you are anything like me, you might be thinking:
β€œIsn't 1% too little? You're gonna take ages to grow!”

Well...

Is 1% that little?

I'll show you it isn't!

First, here's a screenshot of my growth in the beginning of my Twitter journey πŸ‘‡

Let's work with those numbers... Image
Read 32 tweets
29 Sep
I challenged you πŸ†...

You delivered πŸ’ͺ!

I asked you to implement the sign function in Python 🐍.

Now I'll go over some alternatives and tell you what I like βœ… and dislike ❌ about them.

I'll also tell you which one I think is the best, most Pythonic ✨ one.

πŸ‘‡πŸ§΅
By the way, for reference, here is the original challenge:

Let's start with the β€œbasic” `if: ... elif: ... else: ...` approach first.

Gets the job done, is simple, and is easy to ready.

Funnily enough, the only one to share that solution was a _very_ seasoned Python 🐍 programmer, author and trainer, @dabeaz πŸ™ƒ

Now, a couple of notes:
Read 28 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

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

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(