2015-10-04 85 views
0

我試圖將文本文件轉換爲字典,我可以使用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 
+0

@馬丁皮特編輯。 TKS! –

回答

0

當你找到它與:一條線,你有鑰匙,否則你有值,以便值添加到最後的關鍵k

from collections import defaultdict 

d = defaultdict(list) 

with open("test.txt") as fin: 
    for line in fin: 
     if ":" in line: 
      k, v = line.rstrip().split(":") 
      d[k].extend(map(str.strip,v.split(",")) if v.strip() else []) 
     else: 
      d[k].append(line.rstrip()) 
    print(d) 

INOUT:

Cost : 45 
Shape: Square, triangle, rectangle 
Color: 
red 
blue 
yellow 
Foo : 1, 2, 3 
Bar : 
100 
200 
300 

輸出:

from pprint import pprint as pp 
pp(d) 


{'Bar ': ['100', '200', '300'], 
'Color': ['red', 'blue', 'yellow'], 
'Cost ': ['45'], 
'Foo ': ['1', '2', '3'], 
'Shape': ['Square', 'triangle', 'rectangle']} 

您可以輕鬆更改代碼以將每個值放入單個列表中,但我認爲一個列表中的所有值都會更有意義。

+1

我明白了!我試了幾個小時。你真棒!謝謝 –

+0

沒有問題,不客氣。 –

相關問題