"Get" values from dictionaries better.

I'm not saying you're doing it wrong, but... you are.

👋 Hey there!

I don’t know about you, but I’m enjoying writing this newsletter. This week’s snack is a bit long, but I think you’ll like this little tidbit, especially if you’re new to Python programming.

Here’s what’s in store for today’s snack (hint: click/tap one of the bullet points below to jump straight to that section!):

💡 This Week’s Snack: Using.get()

When I first started Python programming and I always used to write my value-fetching-in-a-dictionary code like this:

Fetching dictionary values using try/except

While this is a completely valid way of doing so, there’s a few issues with this:

  1. The try and except block, while more explicit with what you want, makes the code less-readable.

  2. Usage of a try/except block could potentially mask errors. While the example doesn’t reflect a scenario, it could make debugging more difficult.

  3. While it’s small, there’s performance issues with this. The try/except block does require more overhead because it has to catch and raise an exception.

A coworker had introduced and (highly) suggested using .get() instead. If we were to keep the same logic from above but change the function:

Method 2: Using .get() instead

Not only does implementing the method eliminate the points I listed above, but it also adds the following value:

  1. You’ll have more control over the default value; in this case, Key not defined is the default value if the key does not exist.

  2. The code becomes even more explicit as to what you want, whereas the try/except block could imply that you’re catching a special edge case.

For more information about the .get() method, see W3 School's article.

🔦 Python Package Spotlight: Tabulate

Tabulate is a Python package that offers a simple and efficient way to present tabular data in a visually appealing format. It is widely used in data analysis, reporting, and command-line applications where quick and readable table output is desired.

Tabulate example

The package supports various output formats including plain text, grid, and HTML, and can handle data from Python’s built-in data structures such as lists, tuples, and dictionaries.

Key features:

  1. Multiple Table Formats: Tabulate supports a variety of table formats, allowing users to choose the most suitable style for their data presentation.

  2. Automatic Alignment and Column Width: The package automatically adjusts the alignment and width of columns based on the content. This saves time and effort in manually setting up column widths and alignments.

  3. Handling Missing Data: Tabulate is capable of elegantly handling missing data. By default, it will leave cells empty if data is missing, but this behavior can be customized. You can specify a filler value for missing data, ensuring that your tables are always complete and neatly formatted.

You can get started using Tabulate by checking out the documentation located on their Github repository.

💢 Challenge of the Week

This week’s challenge is rated 3 ⭐️⭐️⭐️. Take a stab at it (I’d recommend you use this week’s snack) and let me know what your solution is:

Create a Python script that counts the frequency of each word in a given string. The script should be case-insensitive and consider only alphabetic characters (you can ignore punctuation and numbers).

Here’s 2 test cases:

Test Case 1:
- Input: "Hello world! Hello Python."
- Output: {'hello': 2, 'world': 1, 'python': 1}

Test Case 2:
- Input: "Ask not what your country can do for you - ask what you can do for your country."
- Output: {'ask': 2, 'not': 1, 'what': 2, 'your': 2, 'country': 2, 'can': 2, 'do': 2, 'for': 2, 'you': 2}

» Each challenge is rated on a difficulty of 1 to 5 stars, with 1 star being easy 5 stars being the most difficult.

Did you enjoy this week's snack?

Login or Subscribe to participate in polls.

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate.