1

Here is a simplifed version of a list of dictionaries I from the MailChimp api and I'm using the function to get a sorted list based on timestamp_out. When I run this I get 'none' as the output. It seems this should work. Does anybody know what is going on and how to make it simply output a sorted list? Thanks - and yes, I've searched for this but haven't an answer yet.

 memberList=[{'email_address': 'aaa@gmail.com', 'timestamp_opt': '2020-07-17T00:49:53+00:00'}, {'email_address': 'bbb@yahoo.com', 'timestamp_opt': '2020-07-17T01:29:47+00:00'}]

  def key_function(item_dictionary):
     datetime_string = item_dictionary['timestamp_opt']
     return datetime.datetime.strptime(datetime_string, '%Y-%m-%dT%H:%M:%S%z')


 sortList=memberList.sort(key=key_function)

 print(sortList)
Allen
  • 722
  • 4
  • 13
  • 31

1 Answers1

3

Change this:

sortList = memberList.sort(key=key_function)

to this:

sortList = sorted(memberList, key=key_function)

sort changes the original memberList in-place, and doesn't return anything, which is why you get the None you're seeing. However, sorted returns a new list, which we can assign to sortList.

See What is the difference between sorted(list) vs list.sort()? for further details.

Mario Ishac
  • 5,060
  • 3
  • 21
  • 52