2

複数の辞書を含むリストがあります。各ディクショナリには、日付と時刻のキーがあります。私が理解しようとしているのは、各辞書の値を時系列で行に出力する方法です。

以下は私のコードの例です。

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

これに関する誰かのガイダンスをいただければ幸いです。本当にありがとう。

4

3 に答える 3

3

日付は 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'}
于 2014-02-18T00:57:58.130 に答える