Python Sorting list of dictionaries with nested list

47 Views Asked by At

I have a list of dictionaries (message threads), that contain another list of dictionaries (messages) I need to order the threads by the date of the most current message.

what the data looks like

[
    {key:thread1,
     messages:[
                {key:message1,
                 date:10/10/2023
                 }
                 /// older messages
              ]
    },
    {key:thread2,
     messages: [
                 {key:message4,
                  date:10/13/2023
                  },
                  ///older messages
               ]
      }
]

I need to sort it so that the first in the list would be thread 2 which has the most recent message as appose to thread1, the messages are already correctly sorted already.

2

There are 2 best solutions below

0
DarrylG On BEST ANSWER

Approach

Create a function that use Python sorted function to sort list with a key function and in reverse order

Code

from datetime import datetime   # will use strptime in datetime to convert date string to date object

def sort_by_date(lst):
  ' function to sort by the date of the first message in the list '
  # d['messages'][0]['date'] is the date of first message in list
  # use datetime.strptime to convert string to datetime object for sorting
  return sorted(lst, key = lambda d:  datetime.strptime(d['messages'][0]['date'], "%m/%d/%Y"),
               reverse = True)

Usage

# List to sort
lst = [
    {'key':'thread1',
     'messages':[
                {'key':'message1',
                 'date':'10/10/2023'
                 }
                 # older messages
              ]
    },
    {'key':'thread2',
     'messages': [
                 {'key':'message4',
                  'date':'10/13/2023'
                  },
                  # older messages
               ]
      }
]

print(sort_by_date(lst))  # Use function sort_by_date defined above

Output

Result is thread2 is first

[{'key': 'thread2', 'messages': [{'key': 'message4', 'date': '10/13/2023'}]}, {'key': 'thread1', 'messages': [{'key': 'message1', 'date': '10/10/2023'}]}]
0
Ptolemaic Ptoast On

With an array of the structure you describe as threads, the thread containing the most recent message can be obtained like this:

max(threads,key=lambda x: max(m["date"] for m in x["messages"]))

Be careful with the formatting of those date parameters. If they are strings formatted as month/day/year, max will not reliably return the most recent date. One fix for this would be to cast the date parameters to datetime objects before performing the operation.