2015-11-07 124 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

相关问题