Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
11: for may_date in date_keys: #Loop to convert F to C
12: #
13: high_temp_f = may_high_temp_c[may_date] #Obtain Fahrenheit
14: #
15: high_temp_c = (high_temp_f - 32) * 5 / 9 #Convert to Celsius
16: #
17: may_high_temp_c[may_date] = high_temp_c #Update dictionary
18: #
19: ###########################################################
20: # Display Record High Temps Dictionaries (Both F & C)
21: #
22: print ()
23: print ("Record High Temperatures in Indianapolis during Race Month")
24: #
25: date_keys = may_high_temp.keys() #Obtain list of element keys
26: #
27: for may_date in date_keys: #Loop to display key/value pairs
28: print ("May", may_date, end = ': ')
29: print (may_high_temp[may_date],"F", end = '\t')
30: print ("{0:.1f}".format(may_high_temp_c[may_date]),"C")
...

In Listing 9.12, note that the .update dictionary operation is used on line 7. This operation
performs a deep copy of the dictionary. A deep copy copies both the structure of an object and its
elements. A shallow copy, on the other hand, copies only the structure of an object.


By the Way: The Inefficient Script
The script0902.py script is inefficient in how it has the user enter the data, then
make a copy of the dictionary, and then reenter the Fahrenheit data into another
dictionary. Keep in mind that these scripts are for learning purposes only. If they are to
be used for non-educational purposes, they should be rewritten for efficiency’s sake. In
fact, rewriting them would be a good exercise for you to do as you learn Python
programming!

In Listing 9.12, on line 15, the Fahrenheit temperature is converted to Celsius using a math equation.
You learned about math in Python back in Hour 5, “Using Arithmetic in Your Programs.” Once the
conversion is made, the value in the may_high_temp_c dictionary is updated via an assignment
option. Remember that when you use an existing key during a value assignment, the key simply has its
associated value updated.


In Listing 9.13, you can see the output produced by the script0902.py script. Notice the Celsius
temperature output in Listing 9.13 and then look back to line 30 in Listing 9.12. The format
function, as you learned in Hour 5, enables the proper display of the calculated Celsius temperature.


LISTING 9.13 Output of script0902.py


Click here to view code image


pi@raspberrypi ~ $ python3 py3prog/script0902.py

Enter the record high temps (F) for May in Indianapolis...
Record high for May 1: 88
Free download pdf