2 回答

TA貢獻1807條經驗 獲得超9個贊
sorted_dict = {}
for key, value in sorted(original_dict.items(), key=lambda x:x[1][0], reverse=True):
sorted_dict[key] = value
其中x[1][0]代表字典值的第一項,我相信這是您想要對字典進行排序的內容。反向參數是可選的,如果未提供,則默認為 False。

TA貢獻1804條經驗 獲得超7個贊
基于Python:對列表字典進行排序,您首先需要將時間戳從字符串轉換為時間對象,然后比較它們。
datetime.datetime.strptime()
可以做的工作:將字符串按特定格式轉換為Time 對象。例如:
In [13]: a = datetime.datetime.strptime('2019-02-04 15:29:10', '%Y-%m-%d %H:%M:%S')
In [14]: b = datetime.datetime.strptime('2019-02-04 15:30:10', '%Y-%m-%d %H:%M:%S')
In [15]: b > a
Out[15]: True??
然后你可以用它作為你的鍵對你的字典進行排序,從我提到的答案中找到解決方案。只需作為函數執行dict()即可將結果轉換為字典:
In [17]: dict(sorted(sorted_dict.items(), key=lambda x: datetime.datetime.strptime(x[1][0], '%Y-%m-%d %H:%M:%S')))
Out[17]:
{'Name B': ['2019-01-04 12:21:10',、
'First Line of info',
'Second line of info',
'Third line of info'],
'Name A': ['2019-02-04 15:29:10',
'First Line of info',
'Second line of info',
'Third line of info']}?
In [18]:
添加回答
舉報