Using Look Up Tables in Python

Vishvachi Sinha picture Vishvachi Sinha · May 24, 2018 · Viewed 40.9k times · Source

I am using python to automate a piezoelectric droplet generator. For each value of a pulse length, a suitable value of voltage will be there to produce a signal to give away a droplet. This value of voltage keeps changing in every run(for example, + or -10). So I have a database of different value of voltages for every pulse length.

I would like to know some things about using lookup tables in python. For my task, I want to pick a random pulse length from 15 to 70, and associate this value with a particular range of voltages from the database (for example: for a value 17, I would like the program to access the lookup table and return a range of voltages 35-50). Is it possible to take the entire range and not just a single value. Since, I am new to coding and python, I am not really sure. Any help is welcome. Thank you.

Answer

offeltoffel picture offeltoffel · May 24, 2018

Since we are not given any further information about what ranges should be associated with which values, I assume you will transfer my answer to your own problem.

Look-up-Tables are called dictionary in python. They are indicated by curly brackets.

Easy example:

myDict = {1: [1, 2, 3, 4, 5],
          2: [2, 3, 4, 5, 6],
          3: [3, 4, 5, 6, 7]}

Here you create a dictionary with three entries: 1, 2, 3. Each of these entries has a range associated with it. In the example it is of logic range(i, i+5).

You inquire your "Look-Up-Table" just like a list:

print(myDict[2])
>>> [2, 3, 4, 5, 6]

(Note how [2] is not index #2, but actually the value 2 you were looking for)

Often you do not want to create a dictionary by hand, but rather want to construct it automatically. You can e.g. combine two lists of the same length to a dictionary, by using dict with zip:

indices = range(15, 76) # your values from 15 to 75
i_ranges = [range(i, i+5) for i in indices] # this constructs your ranges
myDict = dict(zip(indices, i_ranges)) # zip together the lists and make a dict from it
print(myDict[20])
>>> [20, 21, 22, 23, 24]

By the way, you are not restricted to integers and lists. You can also go like:

myFruits = {'apples': 20, 'cherries': 50, 'bananas': 23}
print(myFruits['cherries'])
>>> 50