我有一个具有以下格式的 .txt 文件:
Name A
2019-02-04 15:29:10
First Line of info
Second line of info
Third line of info
Name B
2019-01-04 12:21:10
First Line of info
Second line of info
Third line of info
我已使用以下代码将此文件转换为字典,第一行是键,其余值作为列表:
import itertools as it
dict = {}
with open('filenamehere') as f:
while True:
try:
p = next(f).rstrip()
dict[p] = list(l.rstrip() for l in it.takewhile(lambda line: line != '\n', f))
except StopIteration:
break
这将创建一个字典,{'Name A': ['2019-02-04 15:29:10','First line of info','Second line of info','third line of info']等等。然后,我能够按字母顺序对这本词典进行排序,并以与原始文本文件类似的格式显示它:
sorted_dict= {}
sorted_keys = sorted(dict.keys(), key=lambda x:x.lower())
for key in sorted_keys:
sorted_dict.update({key: dict[key]})
for name, details in list(sorted_dict.items()):
print(f"{name}\n" + '\n'.join(details), "\n")
现在我的问题是如何按最新时间戳对该字典进行排序,然后以与原始文本文件类似的格式打印它?
函数式编程
三国纷争
相关分类