1

I am trying to get the max daily temperatures from a CSV file containing the date and temperature (temperature value for every minute of each day). The period spans 6 months and I need the max temperature for each day of the 6 months.

I have two lines of thought on how I could do this:

1: I figured I can use a dictionary with the key as the date (for example, '10/30/18') and the value as a list of the temperatures for that day.

I would need to loop through each row and add the temperature to each corresponding day.

Here's my start but not sure if I am approaching this in the best way

dates={}
for row in reader:
    if row[0] in dates:
        dates[row[0]].append([float(row[2])])
    else:
        tempvalues=[]
        tempvalues.append(float(row[2]))
        dates.update({row[0]:tempvalues})

print(dates)

2: I could use the date as the key again, but only update the value of the temperature if it is greater than the previous value. But I am not sure how to put this sort of if statement in a dictionary loop.

Beska
  • 12,445
  • 14
  • 77
  • 112

2 Answers2

1

I would think something like this should work:

dates={}

for row in reader:
    if row[0] in dates:
        dates[row[0]].append(float(row[2]))
    else:
        dates[row[0]] = [(float(row[2]))]

for k, v in dates.items():
    print (k, max(v))

If you just want to store the highest temperature, this should work:

dates={}

for row in reader:
    if row[0] in dates:
        if dates[row[0]] < float(row[2]):
            dates[row[0]] = float(row[2])
    else:
        dates[row[0]] = float(row[2])

for k, v in dates.items():
    print (k, v)
tgikal
  • 1,667
  • 1
  • 13
  • 27
  • That gets me 1 step closer, now if I wanted to get the temperature value that was the max or min of that list, say "10/30/2018" : [ 95.1, 94.1, 93.1] , is there a function to get the max value AND the associated date? – Maria Scicchitano Jan 14 '19 at 20:49
  • for a list of floats you could use `min(list)` or `max(list)`, if you just want to store the max, a `less < greater` comparison will work. – tgikal Jan 14 '19 at 20:51
  • That did it, thank you!! I see where I can work the logic in the loop now. Much appreciated. – Maria Scicchitano Jan 14 '19 at 20:52
0

you can create dictionary with list comprehension:

#for dicts with
# dates = { '10/30/18':[95.1,94.1,93.1],
#....   }       
min_dates = {date:min(temp)] for (date,temp) in dates}
max_dates = {date:man(temp)] for (date,temp) in dates}
Georgiy
  • 3,158
  • 1
  • 6
  • 18