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

Discussão em 'Python' iniciado por Stack, Agosto 6, 2025.

  1. Stack

    Stack Membro Participativo

    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)

    Continue reading...

Compartilhe esta Página