Reputation: 35
I am a novice with python so forgive me if this seems simple and I can't figure it out...
For a homework assignment we are asked to "Write python code to read the daily temperature data for each month of the year. Make three dictionaries, MinT
, AvgT
, and MaxT
each with the month number (1..12) as the key and a list of values for the minimum, maximum and average daily temperatures for each day in the corresponding month." I need to do this without using pandas and numpy, as those are the next questions for the assignment.
I am struggling to get started. I am trying to start with MinT
to see if I could get the code to work, but have failed multiple times. So far I have...
import csv
weather = csv.DictReader(open(...))
MinT = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
min_t = []
for r in weather:
min_t.append(float(r['LowT']))
The output is all of the minimum values for the year, but I'm unsure how to aggregate the daily data to where I can use the month as the key.
Any help would be appreciated.
Upvotes: 2
Views: 1460
Reputation: 3678
Here's a self contained example using comprehensions:
from random import randint
def generate_temperatures():
return [randint(60, 92) for day in range(randint(28, 31))]
# This simulates loading your data
annual_temperatures = {month_num + 1: generate_temperatures() for month_num in range(12)}
# This calculates the goods :)
avg_monthly_temperature = {month: sum(temp)/len(temp) for (month, temp) in annual_temperatures.items()}
min_monthly_temperature = {month: min(temp) for (month, temp) in annual_temperatures.items()}
max_monthly_temperature = {month: max(temp) for (month, temp) in annual_temperatures.items()}
Upvotes: 0
Reputation: 20571
To create a dictionary where they keys are the numeric months and the values will be lists, you want:
MinT = {1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[], 10:[], 11:[], 12:[]}
However this is easier to initialize with a loop:
MinT = {}
for x in range(12):
MinT[x+1] = []
Or dictionary comprehension:
MinT = {month_num + 1: [] for month_num in range(12)}
Upvotes: 1