将结构化字符串转换为字典

时间:2016-11-18 15:38:41

标签: python string list dictionary

virtualmin domain-list --multiline返回一个结构化字符串,我想将其转换为dicts的字典列表。

字符串看起来像这样(有时缺少值):

do.ma.in.1
    key1a: value1a
    key1b: value1b
    key1c:
    ...
do.ma.in.2
    key2a: value2a
    key2b: value2b
    ...
...

(键:值对在字符串中缩进4个空格)
我想转换成这种形式:

[do.ma.in.1: {key1a: value1a, key1b: value1b, key1c: None ...}, 
do.ma.in.2: {key2a: value2a, key2b: value2b, ...}, ...

到目前为止,我确实用re.split("\s*(?=^\S)", str)拆分了字符串,这让我

[do.ma.in.1\n    key1a: value1a\n    key1b: value1b\n    key1c:\n    ..., 
do.ma.in.2\n    key2a: value2a\n    key2b: value2b\n    ..., ...

其中列表项只是字符串。 (所以没有实际的字典项目)

我从哪里去?

1 个答案:

答案 0 :(得分:1)

如果是我,我就不会使用re。我将逐行浏览数据,并在我去的时候将值分配给适当的dict

from pprint import pprint

data = '''
do.ma.in.1
    key1a: value1a
    key1b: value1b
    key1c:
do.ma.in.2
    key2a: value2a
    key2b: value2b
'''

key = None
result = {}
for line in data.splitlines():
    if not line.strip():
        continue
    line = line.split(':', 1)
    if len(line) == 1:
        key = line[0].strip()
        result[key] = {}
    elif len(line) == 2:
        result[key][line[0].strip()] = line[1].strip()

pprint(result)

结果:

{'do.ma.in.1': {'key1a': 'value1a', 'key1b': 'value1b', 'key1c': ''},
 'do.ma.in.2': {'key2a': 'value2a', 'key2b': 'value2b'}}