# Siv Scripts

Solving Problems Using Code

Wed 27 September 2017

# Dictionary Dispatch

Posted by Aly Sivji in Quick Hits

ChiPy hosts Python Project Night on the 3rd Thursday of every month. Groups of four are given an hour to work through a structured exercise with each person spending 15 minutes at the keyboard writing code. At the end of the hour, one group is selected to present their solution.

Project Night is a great way to practice problem solving and pair programming skills in an encouraging and helpful environment. Volunteer tutors wander the room providing hints or answering questions as needed.

Last week's project involved creating a command line application using the python prompt toolkit. During show and tell, one of the groups used a Python technique called "dictionary dispatch" to replicate the behavior of a switch statement.

In this Quick Hit, we will explore the dictionary dispatch technique.

From the Python data model:

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects.

Everything is an object so we can treat everything like an object.

This includes functions. Python functions are "first-class" objects.

We can:

• assign functions to variables
• store them as data structures
• pass functions as arguments to other functions
• return functions as values

The dictionary dispatch technique will take advantage of this fact.

Let's create a simple calculator program that will take two numbers along with an operation (add, sub, mult, div) and then return a computed result.

We'll define the operation functions as follows:

In :
def add(num1, num2):
return num1 + num2

In :
def subtract(num1, num2):
return num1 - num2

In :
def multiply(num1, num2):
return num1 * num2

In :
def divide(num1, num2):
try:
return num1 / num2
except ZeroDivisionError:
return "Can't divide by 0"

In :
print(divide(5, 5))
print(divide(5, 0))

1.0
Can't divide by 0


We will create a mapping that takes in an operation (key) and assigns it to the appropriate function (value):

In :
func_mapping = {
'sub': subtract,
'mult': multiply,
'div': divide,
}


Let's test to make sure our program works:

In :
op = input('Enter operation (add, sub, mult, div): ')
val1 = int(input('Enter first number: '))
val2 = int(input('Enter second number: '))

print(func_mapping[op](val1, val2))

Enter operation (add, sub, mult, div): div
Enter first number: 5
Enter second number: 0
Can't divide by 0


Looks good!

Based on the selected op, we call the appropriate function to perform a calculation on the entered numbers.

As Python doesn't have a switch or case statement, we can use the dictionary dispatch technique to map functions to case values.

I fleshed out the calculator program into a console app with the argparse module from the Python Standard Library. Code is on Github.