pythonsorting

Sorting Dictionary By Date


I have a dictionary which contains several years of data. The dictionary is basically this:

data = {
  '2024-09-20': 13.37,
  '2024-09-21': 14.92,
  '2024-09-22': 15.17,
  '2024-09-23': 12.15
}

It contains about 10 years of data or so. What I need to do is first limit the range to just the last 5 years, and then choose the largest value.

So, I need to sort it by the key, which is the date in DESC order, then remove anything greater than 5 years, then choose the largest value.


Solution

  • You can easly sort and filter date with datetime.

    Firstly, you need to convert your string into datetime object:
    parsed_data = {datetime.strptime(date_str, '%Y-%m-%d'): value for date_str, value in data.items()}

    Secondly, you will need to filter the date to suppress the one that are more than 5 years old :

    today = datetime.today()
    
    five_years_ago = today - timedelta(days=5*365)
    
    filtered_data = {date: value for date, value in parsed_data.items() if date >= five_years_ago}
    

    Finaly, get the biggest value of your data :

    if filtered_data:
        max_value = max(filtered_data.values())
        print("Max value in the last 5 years:", max_value)
    else:
        print("No data in the last 5 years.")