亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何按字典值的一部分對字典進行排序?

如何按字典值的一部分對字典進行排序?

烙印99 2023-07-05 16:27:22
我有一個具有以下格式的 .txt 文件:Name A2019-02-04 15:29:10First Line of infoSecond line of infoThird line of infoName B2019-01-04 12:21:10First Line of infoSecond line of infoThird line of info我已使用以下代碼將此文件轉換為字典,第一行是鍵,其余值作為列表:import itertools as itdict = {}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")現在我的問題是如何按最新時間戳對該字典進行排序,然后以與原始文本文件類似的格式打印它?
查看完整描述

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。


查看完整回答
反對 回復 2023-07-05
?
三國紛爭

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]:


查看完整回答
反對 回復 2023-07-05
  • 2 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號