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

(singke) #1

Programming with Dictionaries


Put on your weather researcher hat: You are going to do some weather data processing using a
dictionary. In this part of the hour, you will be looking at three different Python scripts that use
dictionaries to store and then analyze weather data.


The first script, script0901.py, populates a dictionary with daily record high temps (Fahrenheit)
in Indianapolis, Indiana, for the month of May. In Listing 9.10, you can see the dictionary used to store
the collected data. Each dictionary element’s key is the day of the month in May. Each key’s
associated value is the logged record high temperature for that day.


LISTING 9.10 The script0901.py Script


Click here to view code image


1: pi@raspberrypi ~ $ cat py3prog/script0901.py
2: # script0901.py - Populate the Record High Temps Dictionary
3: # Author: Blum and Bresnahan
4: # Date: May
5: ###########################################################
6: #
7: # Populate dictionary for Record High Temps (F) during May in Indianapolis
8: print ()
9: print ("Enter the record high temps (F) for May in Indianapolis...")
10: #
11: may_high_temp = {} #Create empty dictionary
12: #
13: for may_date in range (1, 31 + 1): #Loop to enter temps
14: #
15: # Obtain record high temp for date
16: prompt = "Record high for May " + str(may_date) + ": "
17: record_high = int(input(prompt))
18: # Put element in dictionary
19: may_high_temp[may_date] = record_high
20: #
21: ###########################################################
22: # Display Record High Temps Dictionary
23: #
24: print ()
25: print ("Record High Temperatures (F) in Indianapolis during Race Month")
26: #
27: date_keys = may_high_temp.keys() #Obtain list of element keys
28: #
29: for may_date in date_keys: #Loop to display key/value pairs
30: print ("May", may_date, end = ': ')
31: print (may_high_temp[may_date])
32: #
33: #########################################################
34: pi@raspberrypi ~ $

On line 11, the empty dictionary may_high_temp is created. Then, using a for loop, the 31 days
of high temperatures (Fahrenheit) are entered into the dictionary on lines 13–19. The elements in the
dictionary are then pulled out and displayed one by one, using another for loop on lines 29–31.
Notice that to make the values display in the right order, they are retrieved using their key value on
line 27.

Free download pdf