简体   繁体   中英

Sort a Python List of Dictionaries with TimeStamp

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM