Looping over a list to create dict

Question:

I have those lists

dates = ['2022-10-16 17:00:00', '2022-10-16 18:00:00', '2022-10-16 21:00:00', '2022-10-16 22:00:00']

values = [1920.0, 570.0, 1680.0, 900.0]

and I’m trying to create a dict based on morning/night, so i wrote the following code

    def to_dict(self):
        my_dict = {}
        for i in range(len(dates)):
            hour = dt.datetime.strptime(date[i], "%Y-%m-%d %H:%M:%S").hour
            if 6 < hour <= 17:
                my_dict[date[i][:11] + "06:00:00"] = [value[i]]
            else:
                my_dict[date[i][:11] + "00:00:00"] = [value[i]]
        print(my_dict)
        return my_dict

and i want to get these result

{'2022-10-16 06:00:00': [1920.0], '2022-10-16 00:00:00': [570.0, 1680.0, 900.0]}

But somehow I’m getting these instead

{'2022-10-16 06:00:00': [1920.0], '2022-10-16 00:00:00': [900.0]}

Why is it only one value in the list?

Asked By: ilra

||

Answers:

You need to append to a dict entry rather than simply assign to it:

def to_dict(self):
    my_dict = {}
    for date, value in zip(dates, values):
        d = dt.datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
        h = 6 if 6 < d.hour <= 17 else 0
        d = d.replace(hour=h)
        my_dict.setdefault(str(d), []).append(value)
    return my_dict
Answered By: gog
import datetime


dates = ['2022-10-16 17:00:00', '2022-10-16 18:00:00', '2022-10-16 21:00:00', '2022-10-16 22:00:00']

values = [1920.0, 570.0, 1680.0, 900.0]


my_dict = {}

for datetimeStr, value in zip(dates, values):

    datetime_ = datetime.datetime.strptime(datetimeStr, "%Y-%m-%d %H:%M:%S")

    if 6 < datetime_.hour and datetime_.hour <= 17:
        key = datetime_.replace(hour=6).isoformat(sep=" ")
    else:
        key = datetime_.replace(hour=0).isoformat(sep=" ")

    my_dict.setdefault(key, []).append(value)

print(my_dict)
Answered By: hi im Bacon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.