pythondictionarysorting

How to sort a dictionary with list of datetime objects as value?


I have a dictionary with lists of datetime as value:

month_a = [8,9,10]
day_a = [13,12,15]
month_b = [8,9,10]
day_b = [13,11,13]

dt_a=[]
for m,d in zip(month_a, day_a):
    dt_a.append(datetime.datetime(2025, m, d).date())

dt_b=[]
for m,d in zip(month_b, day_b):
    dt_b.append(datetime.datetime(2025, m, d).date())

my_dict = {'A':dt_a, 'B':dt_b}
print('original:')
print(my_dict)

I want to loop through all the datetime values in the list and sort the datetime. Finally a list of tuple with key and value is supposed to be generated . Like this:

list_sorted = [('A', datetime.date(2025, 8, 13)), ('B', datetime.date(2025, 8, 13)), ('B', datetime.date(2025, 9, 11)), ('A', datetime.date(2025, 9, 12)),  
               ('B', datetime.date(2025, 10, 13)), ('A', datetime.date(2025, 10, 15))]

print('sorted:')
print(list_sorted) 

Solution

  • From your dictionary you could build a list of tuples then sort that as follows:

    from datetime import datetime, date
    
    def do_sort(d:dict[str, list[date]]) -> list[tuple[str, date]]:
        combo = []
        for k, v in d.items():
            for e in v:
                combo.append((k, e))
        return sorted(combo, key=lambda e: (e[1], e[0]))
    
    month_a = [8, 9, 10]
    day_a = [13, 12, 15]
    month_b = [8, 9, 10]
    day_b = [13, 11, 13]
    
    dt_a = []
    for m, d in zip(month_a, day_a):
        dt_a.append(datetime(2025, m, d).date())
    
    dt_b = []
    for m, d in zip(month_b, day_b):
        dt_b.append(datetime(2025, m, d).date())
    
    my_dict = {"A": dt_a, "B": dt_b}
    print(my_dict)
    print(do_sort(my_dict))
    

    Output:

    {'A': [datetime.date(2025, 8, 13), datetime.date(2025, 9, 12), datetime.date(2025, 10, 15)], 'B': [datetime.date(2025, 8, 13), datetime.date(2025, 9, 11), datetime.date(2025, 10, 13)]}
    [('A', datetime.date(2025, 8, 13)), ('B', datetime.date(2025, 8, 13)), ('B', datetime.date(2025, 9, 11)), ('A', datetime.date(2025, 9, 12)), ('B', datetime.date(2025, 10, 13)), ('A', datetime.date(2025, 10, 15))]