简体   繁体   中英

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)

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')]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM