Python Advanced #4 - Using Python Dictionaries for Paired Data

This post will demonstrate the use of dictionaries in Python along with showing an example of their use with paired numerical data.

The paired numerical data in this example is a relationship between a water surface elevation in a stream and the corresponding flow.  However, this coding will work for any paired numerical data.

First, an example of a dictionary and its use is needed.  In the figure below, we have a dictionary titled, "paired_data".  Note that a dictionary is defined with {}.  In this dictionary, we have the keys 1, 2, 3, and 4.  Associated with these keys are the values of 100, 200, 300, and 400.



In the print statement, we are asking that Python print the value corresponding to a key of 2 in the dictionary, "paired_data".

The following is the result:




Just as with a regular dictionary where a word can have multiple definitions, a key in a Python dictionary can have multiple values associated with it.  In the example below, we create an empty dictionary named "pairs".

We then populate "pairs" with multiple values for the key, "elevation", and multiple values for the key, "flow".  Note that the same information as above is used, it is simply in a slightly different format.

In the remainder of the coding, we perform the following steps:


  • Ask the user to input an elevation
  • We extract the elevation and flow values that bracket the input elevation
  • We write a function to interpolate using the upper and lower elevation and flow values
  • We call the function 
  • We print out the value of the flow




The result of running the program is shown below.



Comments

Table Rock Dam

Table Rock Dam