我試圖將文本文件轉換爲字典,我可以使用defaultdict
這樣做。將文本文件轉換爲包含一個鍵和多個值的字典
產量良好,預期。但我現在關心的是如何進一步拆分我的值,如果我的格式的txt文件不只是「:」,而且還有「,」和「(間距)」?我嘗試插入一些循環,但它沒有工作,所以我刪除了它們。
例如:
Cost : 45
Shape: Square, triangle, rectangle
Color:
red
blue
yellow
所需的輸出:
{'Cost' ['45']}
{'Shape' ['Square'], ['triangle'], ['rectangle'] }
{'Color' ['red'], ['blue'], ['yellow']}
這裏是我當前的代碼。我應該如何修改它?
#converting txt file to dictionary with key value pair
from collections import defaultdict
d = defaultdict(list)
with open("t.txt") as fin:
for line in fin:
k, v = line.strip().split(":")
d[k].append(v)
print d
@馬丁皮特編輯。 TKS! –