Romeo
Romeo

Reputation: 147

How to read a multiline values into a dictonary

I have file1 in format

field1-name, initial-val, desc
field2-name, initial-val, desc
field2-name, initial-val, desc
end-group1

field1-name, inital-val, desc
end-group2

.....

I need create a dictionary of groups with group as key and list of fields as value

group1: [(field1-name, initial-val, desc), (field2-name, inital-val, desc),(...)]
group2: [(field1-name, initial-val, desc)]

What's the most Pythonic way to read this file and convert it into groups. I have code that reads line-by-line and parse/stores value, but was wondering if there is better way.

psedo-code
group = {}
with open(file, 'r') as f:
   for line in f:
      if line.startswith(r/end/):
          #extract group-name and create a tuple for field values
          group[group-name] = new_group
          new_group = []
          continue
      new_group.append(line)

Upvotes: 0

Views: 36

Answers (1)

blhsing
blhsing

Reputation: 106588

Reading the file line-by-line is the most fitting solution given your file format being a mixed one, requiring a conditional statement to determine whether to append to a sub-list or to create a new dict entry:

group = {}
rows = []
with open(file, 'r') as f:
    for line in f:
        line = line.rstrip()
        if line.startswith('end-'):
            group[line.replace('end-', '', 1)] = rows
            rows = []
        elif line:
            rows.append(tuple(line.split(', ')))

group becomes:

{'group1': [('field1-name', 'initial-val', 'desc'),
            ('field2-name', 'initial-val', 'desc'),
            ('field2-name', 'initial-val', 'desc')],
 'group2': [('field1-name', 'inital-val', 'desc')]}

Upvotes: 1

Related Questions