Reputation: 9
I have a file like this :
group #1
a b c d
e f g h
group #2
1 2 3 4
5 6 7 8
How can I make this into a dictionary like this:
{'group #1' : [[a, b, c, d], [e, f, g, h]],
'group #2' :[[1, 2, 3, 4], [5, 6, 7, 8]]}
Upvotes: 0
Views: 1578
Reputation: 85765
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
Output:
{'group #2': [['1', '2', '3', '4'], ['5', '6', '7', '8']],
'group #1': [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]}
Upvotes: 3
Reputation: 309831
Iterate over the file until you find a "group" tag. Add a new list to your dictionary with that tag. Then append lines to that tag until you hit another "group" tag.
untested
d = {}
for line in fileobject:
if line.startswith('group'):
current = d[line.strip()] = []
elif line.strip() and d:
current.append(line.split())
Upvotes: 1