...
Record High Temperatures in Indianapolis during Race Month
May 1: 88 F 31.1 C
May 2: 85 F 29.4 C
May 3: 88 F 31.1 C
...
pi@raspberrypi ~ $
Now you have a script that gets the temperature data into a dictionary and a script that calculates the
Celsius values. Finally, you need a script that allows you to do some calculations on the temperatures
for your pretend weather research.
Listing 9.14 shows part of script0903.py. This Python script takes the temperature data in a
dictionary and calculates the maximum, the minimum, and the mode of the high temperatures.
LISTING 9.14 The script0903.py Script
Click here to view code image
1: pi@raspberrypi ~ $ cat py3prog/script09023.py
2:
...
3: # Determine Maximum, Minimum, and Mode Temps
4: #
5: temp_list = may_high_temp.values()
6: max_temp = max(temp_list) #Determine maximum high temp
7: min_temp = min(temp_list) #Determine minimum high temp
8: #
9: # Determine mode (most common) high temp ###
10: #
11: # Import Counter function
12: from collections import Counter
13: #
14: # Count temps and take the most frequent (mode) temperature
15: mode_list = Counter(temp_list).most_common(1)
16: #
17: # Extract mode high temp from 2-dimensional mode list
18: mode_temp = mode_list[0][0]
19: #
20: print ()
21: print ("Maximum high temp in May:\t", max_temp,"F")
22: print ("Minimum high temp in May:\t", min_temp,"F")
23: print ("Mode high temp in May:\t\t", mode_temp,"F")
...
Calculating the maximum and minimum temperatures is easy. You simply grab the values from the
dictionary, on line 5, using the .values operation. Next you use the built-in max or min function
on the values. Determining the mode of the high temperatures takes a little more work.
Did You Know: What Is Mode?
In a list of values, the mode is the value that occurs the most often. Thus, in the list 1, 2,
3, 3, 3, the number 3 is the list’s mode.