【问题标题】:How to read a multiline values into a dictonary如何将多行值读入字典
【发布时间】:2019-10-21 00:30:18
【问题描述】:

我有 file1 格式

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

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

.....

我需要创建一个组字典,其中组为键,字段列表为值

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

读取此文件并将其转换为组的最 Pythonic 方式是什么。我有逐行读取和解析/存储值的代码,但想知道是否有更好的方法。

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)

【问题讨论】:

  • 如果字段名以“end”开头怎么办?您确定字段名称永远不会以“end”开头吗?

标签: python multiline


【解决方案1】:

考虑到您的文件格式是混合格式,逐行读取文件是最合适的解决方案,需要条件语句来确定是追加到子列表还是创建新的 dict 条目:

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 变为:

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

【讨论】:

    猜你喜欢
    • 2020-07-11
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2015-07-06
    • 2016-02-24
    相关资源
    最近更新 更多