Home > Net >  turning arrays into a dictionary
turning arrays into a dictionary

Time:01-05

im trying to turn two arrays of same length (first is date as a string, second one is a double) into a dictionary with the year as the key and zip of date and double as value.

first question is after adding these would the values keep their order because i know keys wont. (the data is appended in order)

second question is why isnt it working:

from datetime import datetime
def group_by_year(arr,raindata):
    years = []
    Data={}
    for i in range(len(arr)):
        temp = datetime.strptime(arr[i], '%d.%m.%Y').year
        if temp not in years:
            years.append(temp)
            Data[temp]= None
        for key in Data:
            if temp == key:
                Data[key] = zip(arr[i],raindata[i])
    return Data

dates = ['01.03.2021','01.04.2021','01.01.2022']
rain = [0,5,8]
print(group_by_year(dates,rain))

expected output would be

{ 2021: [ ('01.03.2021',0), ('01.04.2021',5) ], 2022: [ ('01.01.2022',0) ] 

CodePudding user response:

Here's one way to solve this:

from datetime import datetime


def group_by_year(arr, raindata):
    Data = {}

    for x in zip(arr, raindata):
        year = datetime.strptime(x[0], "%d.%m.%Y").year
        Data.setdefault(year, []).append(x)

    return Data

dates = ["01.03.2021", "01.04.2021", "01.01.2022"]
rain = [0, 5, 8]
print(group_by_year(dates, rain))

Your original code is not creating a default empty list value for items in the dictionary and the code is unnecessarily iterating over the keys of the dictionary to find a given key.

  • Related