我有一个这样的字符串:
COLUMN 1:
A: 10.68
B: 11.82
C: 12.93
D: 50.2
C 2:
Z: 68
S: 182
W: 13
E: 50
在像字典这样的数据结构中保存此信息的好方法是什么?
更新:问题是,标题不一定以我的实际文本中的COLUMN开头,每个标题下的元素数量可能与另一个不同。唯一的区别元素是在每个标题下,元素用4个空格缩进。
答案 0 :(得分:1)
受到@Vor答案的启发。
result, root = {}, None
for i in q.split('\n'):
if i.strip().endswith(':'):
root = i.strip()
result[root] = {}
elif i:
val = list(map(lambda x: x.strip(), i.split(':')))
result[root].update({val[0]: val[1]})
print(result)
遵守规则:
:
:
更改是您可以将每个根密钥Column X
存储在var中,并检查此根密钥上方的所有行,然后迭代并更新此密钥。
答案 1 :(得分:0)
你可以像这样创建嵌套的dict:
q = '''
COLUMN 1:
A: 10.68
B: 11.82
C: 12.93
d: 50.2
COLUMN 2:
Z: 68
S: 182
W: 13
E: 50
'''
result = {}
for line in q.split('\n'):
if line.strip() and not line[0].isspace():
col = line.strip()[:-1]
result[col] = {}
elif line.strip():
key, value = line.split(':')
result[col][key.strip()] = value.strip()
print result
结果:
{'COLUMN 2': {'S': '182', 'Z': '68', 'E': '50', 'W': '13'}, 'COLUMN 1': {'A': '10.68', 'C': '12.93', 'B': '11.82', 'd': '50.2'}}
或者,如果订单很重要,您可以制作COLUMN x
- 列表并按顺序附加项目
答案 2 :(得分:0)
类似于轻微的调整:
res = {}
for row in data.split('\n'):
if row[:4] != ' ':
res[row.strip(':')] = sub = {}
else:
k,v = row.split(':')
sub[k.strip()] =v.strip()
print res
输出是:
{'C 2': {'S': '182', 'Z': '68', 'E': '50', 'W': '13'}, 'COLUMN 1': {'A': '10.68', 'C': '12.93', 'B': '11.82', 'D': '50.2'}}
如果订单很重要,请改用ordered_dict