2012-12-01 42 views
0

我有一個這樣的文件:如何創建字典從文件在python

group #1 
a b c d 
e f g h 

group #2 
1 2 3 4 
5 6 7 8 

我怎樣才能讓這個變成這樣的詞典:

{'group #1' : [[a, b, c, d], [e, f, g, h]], 
'group #2' :[[1, 2, 3, 4], [5, 6, 7, 8]]} 
+6

的,什麼是你到目前爲止試試?什麼都行不通,是什麼,你現在在掙扎什麼? –

回答

1

遍歷文件,直到你找到一個「組」標籤。使用該標籤將新列表添加到您的字典中。然後將行添加到該標籤,直到您再次碰到另一個「組」標籤。

未經檢驗

d = {} 
for line in fileobject: 
    if line.startswith('group'): 
     current = d[line.strip()] = [] 
    elif line.strip() and d: 
     current.append(line.split()) 
3
file = open("file","r")      # Open file for reading 
dic = {}          # Create empty dic 

for line in file:        # Loop over all lines in the file 
     if line.strip() == '':    # If the line is blank 
      continue       # Skip the blank line 
     elif line.startswith("group"):  # Else if line starts with group 
      key = line.strip()    # Strip whitespace and save key 
      dic[key] = []      # Initialize empty list 
     else: 
      dic[key].append(line.split())  # Not key so append values 

print dic 

輸出:

{'group #2': [['1', '2', '3', '4'], ['5', '6', '7', '8']], 
'group #1': [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]} 
+0

您可能需要'dic [key] .append(..)'中的'line.split()'來匹配OP所需的內容。 –

+0

好點,編輯。 –

+0

NP。我喜歡所有的評論! :-) –