2015-11-07 121 views
2

我有一個列表,並在列表中列出了一個字典,我想按照字典的值對列表進行排序。Python按列表中字典的值對列表進行排序

這是如何工作的?

[{'id': 0, 'thread': 'First', 
'post': [ 
      {'id': 0, 'title': 'MyPost', 'time': '2015-11-07 01:06:08.939687'}] 
}, 
{'id': 1, 'thread': 'Second', 
'post': [ 
      {'id': 0, 'title': 'MyPost', 'time': '2015-11-07 01:06:42.933263'}]}, 
{'id': 2, 'name': 'NoPosts', 'post': []}] 

我想按照第一篇文章的時間對我的Threadlist進行排序,這可能嗎?

回答

3

您可以通過排序或排序的關鍵功能:

In [11]: def key(x): 
      try: 
       return x["post"][0]["time"] # return ISO date string 
      except IndexError: 
       return "Not a date string" # any letter > all date strings 

In [12]: sorted(d, key=key) 
Out[12]: 
[{'id': 0, 
    'post': [{'id': 0, 'time': '2015-11-07 01:06:08.939687', 'title': 'MyPost'}], 
    'thread': 'First'}, 
{'id': 1, 
    'post': [{'id': 0, 'time': '2015-11-07 01:06:42.933263', 'title': 'MyPost'}], 
    'thread': 'Second'}, 
{'id': 2, 'name': 'NoPosts', 'post': []}] 
+0

不需要被'迴歸浮動(「男」)'的'#的NaN>所有日期strings'是真的嗎?然後,你鬆散的Python 3的支持... – dawg

+0

沒有'時間'的職位期望的行爲是沒有指定的,所以''奈'聽起來不錯。 – TigerhawkT3

+1

但''NaN「'只是一個字符串。它需要'float('NaN')'實際上是'nan'號。 Python3會拋出'TypeError:無法定義的類型:float() dawg

相關問題