0

I have a multiline string, and I want to convert into Dict. the multiline string seems like

text='''
     one:
        two:
            three
            four
        five:
            six
            seven
     '''

And i did,

result={}
step1=step2=step3=''
lines=text.split('\n')

the following code that I tried to convert that 'text' to Dict

for line in lines:
    if re.search(r'^(\w+):$',line,re.M):
        out=re.search(r'^(\w+):$',line,re.M)
        step1=out.group(1)
        result[step1]={}
    if re.search(r'^\s{4}(\w+):$',line,re.M):
        out=re.search(r'^\s{4}(\w+):$',line,re.M)
        step2=out.group(1)
        result[step1][step2]={}
    if re.search(r'^\s{8}(\w+)$',line,re.M):
        out=re.search(r'^\s{8}(\w+)$',line,re.M)
        item1=out.group(1)
        result[step1][step2]=[]
        result[step1][step2].append(item1)

print(result)

But when I ran this code I'm getting output like:

{'one': {'two': ['four'], 'five': ['seven']}}

And the Expected result should be:

{'one': {'two': ['three','four'], 'five': ['six','seven']}}

Can anyone help me with this ...

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
qwerty
  • 1
  • 2

1 Answers1

0

Change

result[step1][step2]=[]
result[step1][step2].append(item1)

To

if not result[step1][step2]:
    result[step1][step2]=[item1]
else:
    result[step1][step2].append(item1)

Also you can write your parse logic as follows:

for line in lines:
    out = re.search(r'^(\w+):$',line,re.M)
    if out:
        step1 = out.group(1)
        result[step1] = {}
        continue
    out = re.search(r'^\s{4}(\w+):$',line,re.M)
    if out:
        step2 = out.group(1)
        result[step1][step2] = []
        continue
    out = re.search(r'^\s{8}(\w+)$',line,re.M)
    if out:
        item = out.group(1)
        result[step1][step2].append(item)
Fogmoon
  • 569
  • 5
  • 16