2

I have a list containing multiple dictionaries. Each Dictionary will have a date and time Key. What I am trying to figure out is how print the values of each dictionary to a line in chronological order.

Below is an example of my code.

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)

The expected output would look like this:

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

I would greatly appreciate anyone's guidance on this. Thanks so much.

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 回答
0

我没有花时间为你格式化漂亮的东西,但这是一种快速而肮脏的方式来对它们进行排序。由于您的日期格式很好,因此可以轻松排序。这不像其他答案那样有效,因为我正在用冗余数据构建一个全新的字典。

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)

d = {d['Datetime']:d for d in list_of_dicts} # dictionary comprehension

for k in sorted(d.keys()):
    print(d[k])
于 2014-02-18T01:18:36.283 回答
0

Use http://docs.python.org/2/library/functions.html#sorted with a lambda function. It works for more deeply nested dictionaries as well.

sorted_entries = sorted(list_of_dicts,key=lambda x:x['Datetime'])
于 2014-02-18T01:03:38.647 回答