-1

I read strings from a file that looked like this:

date,temperature
0101, 55
0101, 43
0101, 22
0102, 12
0102, 32
0103, 56
0104, 99

and converted them into 2 lists:

date = [0101, 0101, 0101, 0102, 0102, 0103, 0104]
temperature = [55, 43, 22, 12, 32, 56, 99]

my final goal is to get an output where i have the maximum temperature per day, so I think the first step would be to create a dictionary where I assign the day as the key and the temperatures as the values:

datetemperature = {0101: [55,43,22], 0102: [12, 32], 0103: [56], 0104: [99]}

I tried iterating, but then I only get one value for the temperature. Zip does not really work as I cannot get the correct temperatures and dates together. Is there a way to solve this problem without importing pandas or numpy?

Here is what I have tried so far, however I find it hard to grasp my mind around how I should approach this problem

  stations = []
days = []
temperatures = []

singledays = []
singlestations = []
singletemps = []

stationtemp = {}

for line in Lines:
    (station, day, ac, ad, af, ag, ah, aj, temp, al, ae, ar, at, ay, au, ai, alc, ap, ax, av, an) = line.strip().split(',')

stations.append(station)
days.append(day)
temperatures.append(temp)

for day in days: 
    if day in singledays:
        continue
    else:
        singledays.append(day)
        
for station in stations: 
    if station in singlestations:
        continue
    else:
        singlestations.append(station)
        
stationtemp = dict(zip(stations, temperatures))
Real Kubus
  • 17
  • 4
  • 1
    Could you include the code you have so far? https://stackoverflow.com/help/minimal-reproducible-example – David Dec 01 '20 at 18:42
  • What did you try? I don't see any code, or actual output or anything at all. – Mad Physicist Dec 01 '20 at 18:43
  • @Bjorn I added my workings so far. However the problem is much bigger so I thought I would just state the simple explanation for the smaller problem. – Real Kubus Dec 01 '20 at 18:49
  • Does this answer your question? [Make a dictionary with duplicate keys in Python](https://stackoverflow.com/questions/10664856/make-a-dictionary-with-duplicate-keys-in-python) – Tsubasa Dec 01 '20 at 18:56

4 Answers4

1

Simply add a key each time you encounter a new date and append to the existing key if you have already made it.

Assuming temperature is the name of your list of temperatures and date is your list of dates, this should work:

fin_dict = dict()
for i in range(len(date)):
    if date[i] in fin_dict:
        fin_dict[date[i]].append(temperature[i])
    else:
        fin_dict[date[i]] = [temperature[i]]
0

This kind of works:

weather = """
date,temperature
0101, 55
0101, 43
0101, 22
0102, 12
0102, 32
0103, 56
0104, 99
""".strip()

# Skip the first row
lines = weather.splitlines()[1:]

# Create a dictionary
# Iterate each line
# If the key doesn't exist, create one equal to empty list
# Otherwise, append temperature to list
# This also uses an interim dictionary (tmp).
out = {}
tmp = {}
for line in lines:
    d, t = line.replace(" ", "").split(",")
    if not d in tmp:
        tmp[d] = []
    tmp[d].append(t)
    out[d] = sorted(tmp[d], reverse=True)

Result:

{'0101': ['55', '43', '22'],
 '0102': ['32', '12'],
 '0103': ['56'],
 '0104': ['99']}

EDIT: If you want just max temp per day, then evaluate each value against current values for the given key.

for line in lines:
    d, t = line.replace(" ", "").split(",")
    if d in out:
        if t > max(out[d]):
            out[d] = t
    else:
        out[d] = t

Result:

{'0101': '55',
 '0102': '32',
 '0103': '56',
 '0104': '99'}
Mark Moretto
  • 2,344
  • 2
  • 15
  • 21
0

With simply nested for loops, you should be able to get it done:

date = ['0101', '0101', '0101', '0102', '0102', '0103', '0104']
temperature = [55, 43, 22, 12, 32, 56, 99]
datetemperature = {}
for x in set(date): #this returns unique dates
    datetemperature[x] = [] #a list that holds all temperatures corresponding to a unique date 
    for k,v in enumerate(date): #runing a for loop on the enumerated date list, so as to keep track of the indices
        if v == x:
            datetemperature[x].append(temperature[k])

Output

{'0104': [99], '0101': [55, 43, 22], '0103': [56], '0102': [12, 32]}
Seyi Daniel
  • 2,259
  • 2
  • 8
  • 18
0

You don't need to build an intermediate dictionary. You can let the dictionary constructor do the work for you by supplying it with the date/temperature pairs in ascending order of temperatures. Only the last (i.e. highest) temperature value will remain for each key (date):

date = ["0101", "0101", "0101", "0102", "0102", "0103", "0104"]
temperature = [55, 43, 22, 12, 32, 56, 99]

dayMax = { d:t for t,d in sorted(zip(temperature,date)) }

print(dayMax) # {'0102': 32, '0101': 55, '0103': 56, '0104': 99}

If, for some other reason, you do need the intermediate dictionary with the list of temperatures for each date, you can build it like this:

dayTemps = {d:[] for d in date}
for d,t in zip(date,temperature): dayTemps[d].append(t)

print(dayTemps)
# {'0101': [55, 43, 22], '0102': [12, 32], '0103': [56], '0104': [99]}
Alain T.
  • 40,517
  • 4
  • 31
  • 51