Maciej Zalwert
4 min readApr 9, 2021
Image by Egor Kamelev from Pexels

Python quick tip: DICT or IF for getting a value? Performance & memory battle within python standard modules.

Are you afraid of unknowns, and you always stay with only one way of implementation? Or you want to be a better python programmer?

Let me show you on why to use dict instead of if statements in your python program.

Background:

If statements and dicts are present in every modern programming language. Whereas if statements are especially designed to control flow of operations of a program, dicts are a data structures. Nevertheless, dicts may be used to control flow of operations the same as if statements, or even better!

Let’s see an example!

This is an example of if statement in python. We are going to print animal’s sound. So for example a cat’s sound is “meow” etc…

animals = ['cat', 'lion', 'puma']for animal in animals:
if animal == 'cat':
print('meow')
if animal == 'lion':
print('roar')
if animal == 'puma':
print('rrrr')

Now we are going to do the same with usage of a dict:

dict_example = {'cat': 'meow',
'lion': 'roar',
'puma': 'rrrr'}
for animal in animals:
print(dict_example[animal])

Both methods output the same — but which one is a better?

Let’s go to the battle:

The first step is to prepare a lot bigger dataset.

Note: for a small dataset the difference is so small that it’s no difference whether we use a dict or if statements.

# Data configuration
RANGE = 10000
WORD = 'value'
random_values = [randint(0, RANGE) for p in range(0, RANGE)]

As you can see above we generate 10k random integer values. This is used to have a random queries for both dict and if statement. (you will see in a moment).

Now we initialize empty lists to store values from our queries:

if_list = []
dict_list = []

Below we need to build a dict. For a key we set an integer from a RANGE (defined before) and as for value…

Maciej Zalwert

Data Scientist with 5+ years of broad-based experience in building data-intensive solutions for diverse industries