我有一个这样的文件:
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]]}
我有一个这样的文件:
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]]}
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']]}
遍历文件,直到找到“组”标签。使用该标签将新列表添加到您的字典中。然后将行附加到该标签,直到您点击另一个“组”标签。
未经测试
d = {}
for line in fileobject:
if line.startswith('group'):
current = d[line.strip()] = []
elif line.strip() and d:
current.append(line.split())