-1

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) ] 
  • What is the expected output for your sample input? – jarmod Jan 04 '23 at 17:42
  • @alikoulani keys [keep their order](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) since Python 3.6. – Ignatius Reilly Jan 04 '23 at 18:00
  • _"why isnt it working"_: What does it do? Being able to describe how your program deviates from your expectations is an important first step to being able to fix your program. [How to debug small programs.](//ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Pranav Hosangadi Jan 04 '23 at 18:00
  • `if temp not in years`: You don't need to keep a separate list of years. `temp not in Data` will do the same thing: Check if `temp` is one of the keys in `Data`. Also what if `temp` _is_ in `years` (or `Data`)? – Pranav Hosangadi Jan 04 '23 at 18:02
  • python terminology note: *list* not array, *float* not double. – juanpa.arrivillaga Jan 04 '23 at 18:12

1 Answers1

0

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.

jarmod
  • 71,565
  • 16
  • 115
  • 122