pisit-heng-FQvadXmA524-unsplash.jpg
if else vs. Dictionary in Python
Khuyen Tran

Khuyen Tran

Introduction

You’ve probably used Python dictionaries in the past, but did you know that they can be an alternative to if/else statements? Although Python dictionaries are a pretty common tool, many people don’t know all the ways you can use them to write better code.

Defaults vs. If/Else

Imagine we have the list of animals at the zoo:

animal_list = {
  'lion': 8,
  'tiger': 7,
  'giraffe': 3,
}

If we wanted to find the price of the item but think that some items might be missing from the list, our first option might be to define a new function, such as the following:

def find_animal(animal):
  if animal in animal_list:
      return f'The number of {item}s is {animal_list[item]}'
  else:
      return f'The number of {item}s is not available!'
>>> find_animal('lion')
'There number of lions is 8'
>>> find_animal('dog')
'There number of dogs is not available!'

Great -- our function does the trick, and gives us a nice error if our animal doesn’t exist. So what’s the problem with our approach here? Well, firstly, we query the dictionary twice and use two statements just to return a similar thing. It would be better if there was a way to get a default value if the item isn’t in the list.

Luckily, Python’s dictionary provides that method using get

def find_animal(animal):
  return f'The price for {animal} is {animal_list.get(animal, "not available")}'

.get() looks up a key and returns default value if the animal doesn’t exist. The code definitely looks shorter, but does it work?

>>> find_animal('lion')
'There number of lions is 8'
>>> find_animal('cauliflower')
'The number of cauliflowers is not available!'

Great!

This works great for things that are already dictionaries - but not everything is a dictionary. Can you use this same technique in other places in your Python code? Let’s take the following example.

Imagine you want to create a function that returns a value for operation between 2 numbers. So this is what you come up with:

def operations(operator, x, y):
  if operator == 'add':
      return x + y
  elif operator == 'sub':
      return x - y   
  elif operator == 'div':
      return x / y
  elif operator == 'mul':
      return x * y

You could use this snippet like this:

>>> operations('mul', 3, 8)

24

This works, but we can utilize dictionaries and the get() method to write a more concise function.

def operations(operator, x, y):
  return {
      'add': lambda: x+y,
      'mul': lambda: x*y,
      'sub': lambda: x-y,
      'div': lambda: x/y,
  }.get(operator, lambda: 'Invalid operation')()

Names of the operator become the keys and lambda allows use to use the functions into the values. We can then use get() to return a default value when no key is found. Let’s check our function:

>>> operations('mul', 2, 8)
16
>>> operations('unknown', 2, 8)
'Invalid operation'

Great!

Is a dictionary always the best choice?

Our alternative is shorter - but if we want to use a dictionary like this, we should consider the potential performance hit. Every time we call our method, it creates a temporary dictionary of lambdas for the opcode, which slows down the performance of the function.

If we want to use dictionaries like the above, we should consider creating the dictionary once before the function call, which prevents the code from creating these temporary objects every time we lookup.

I like to write about basic mathematical and programming concepts and play with different data science tools. Follow me on Medium or my blog to get updated about my latest articles. You could also connect with me on LinkedIn and Twitter.

Reference

Bader, Dan. “Python Tricks.” 2017

Need to share Python analyses?

Datapane is an API and framework which makes it easy for people analysing data in Python to publish interactive reports and deploy their analyses.

© 2020 Datapane. All rights reserved. Terms of Service

0.6.11 (v0.6.11-0-g65d1cfd4)