Python 字典列表,按时间顺序排序和打印值

标签 python python-2.7 python-datetime

我有一个包含多个词典的列表。每个词典都有一个日期和时间键。我想弄清楚的是如何将每个字典的值按时间顺序打印到一行。

下面是我的代码示例。

list_of_dicts = []

dict1 = {'Source': 'Log1', 'Type': 'Connection', 'Datetime': '2014-02-13 14:10:00', 'fullpath':'N/A'}
dict2 = {'Source': 'Log2', 'Type': 'Disconnect', 'Datetime': '2014-05-13 11:00:00', 'fullpath':'N/A'}
dict3 = {'Source': 'Log4', 'Type': 'Other', 'Datetime': '2014-05-10 02:50:00', 'fullpath':'N/A'}

list_of_dicts.append(dict1)
list_of_dicts.append(dict2)
list_of_dicts.append(dict3)

预期输出如下所示:

Datetime                Source  Type        Fullpath
2014-02-13 14:10:00     Log1    Connection  N/A
2014-05-10 02:50:00     Log4    Other       N/A
2014-05-13 11:00:00     Log2    Disconnect  N/A

我非常感谢任何人对此的指导。非常感谢。

最佳答案

您的日期采用 ISO8601 格式进行格式化,使其可以按字典顺序排序。

只需按每个词典的 Datetime 键对列表进行排序即可:

from operator import itemgetter

for entry in sorted(list_of_dicts, key=itemgetter('Datetime')):
    # format your output

演示:

>>> list_of_dicts = [
...     {'Source': 'Log1', 'Type': 'Connection', 'Datetime': '2014-02-13 14:10:00', 'fullpath':'N/A'},
...     {'Source': 'Log2', 'Type': 'Disconnect', 'Datetime': '2014-05-13 11:00:00', 'fullpath':'N/A'},
...     {'Source': 'Log4', 'Type': 'Other', 'Datetime': '2014-05-10 02:50:00', 'fullpath':'N/A'},
... ]
>>> from operator import itemgetter
>>> for entry in sorted(list_of_dicts, key=itemgetter('Datetime')):
...     print entry
... 
{'Source': 'Log1', 'fullpath': 'N/A', 'Type': 'Connection', 'Datetime': '2014-02-13 14:10:00'}
{'Source': 'Log4', 'fullpath': 'N/A', 'Type': 'Other', 'Datetime': '2014-05-10 02:50:00'}
{'Source': 'Log2', 'fullpath': 'N/A', 'Type': 'Disconnect', 'Datetime': '2014-05-13 11:00:00'}

关于Python 字典列表,按时间顺序排序和打印值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21842302/

相关文章:

python - 如何粗化二维数组数据分辨率

python - 为什么numpy的效率不成比例

python - Dijkstra算法随机选择具有相同最小权重的相邻节点

python - 将 Cloudinary 图像上传链接到 Django 模型字段

python - dtype=datetime64[ns] 和日期之间的比较无效

python - 如何计算两个日期之间的季度数

Python Cleaner 获取字符串中所有子字符串的方法

python - 组合可能的不同数据格式列表

python-2.7 - 关于ROS包的必要性

python - 如何将时差限制在同一天?