[英]How to read a multiline values into a dictonary
我有 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)
考虑到您的文件格式是混合格式,逐行读取文件是最合适的解决方案,需要一个条件语句来确定是 append 到子列表还是创建新的 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')]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.