Software engineering and personal development

Month: February 2023

How to Get Default Values for Missing Keys in Python

Working with dictionaries in Python is a common task for many programmers, as it allows them to store and manipulate data in a key-value format. However, sometimes we may need to access a key in a dictionary that does not exist, and we want to provide a default value in such cases. The get() method in Python provides a simple and elegant solution to this problem.

The get() method is used to retrieve the value of a specified key in a dictionary. It takes two parameters: the key to look for and a default value to return if the key is not found in the dictionary. If the key is present in the dictionary, get() returns the corresponding value. Otherwise, it returns the default value specified.

Let’s look at the following code snippet:

dictionary = {'first_element': 1, 'second_element': 2}

print(dictionary.get('third_element', 3))  # 3

In this code, we have a dictionary with two key-value pairs. We then use the get() method to retrieve the value associated with the key 'third_element'. Since this key is not present in the dictionary, the method returns the default value of 3.

Continue reading

How to Perform Math Operations Inside Strings in Python

In Python, it’s possible to perform mathematical operations inside of string literals, using a feature called “f-strings”. F-strings, or “formatted string literals”, allow you to embed expressions inside string literals, which are evaluated at runtime. This allows you to mix variables, arithmetic expressions, and other computations into strings in a very readable and convenient way.

num_val = 42

print(f'{num_val % 2 = }') # num_val % 2 = 0

Here, the f-string '{num_val % 2 = }' is a string literal that contains an expression num_val % 2. The % operator is used to perform the modulo operation, which returns the remainder of the division of one number by another. In this case, num_val % 2 returns the remainder of the division of 42 by 2, which is 0.

Continue reading

© 2024 Fatos Morina

Theme by Anders NorenUp ↑