2

I have a dictionary that I have modified by pulling from a file and modifying values, and now I want to put it back in a file in a similar format.

dictionary is similar to the following:

d={'a':
    {'c':'something else',
     'd':{'e':'some item'}
    },
   'b':
    {'z':'something else',
     's':{'f':'some item'}
    }
  }

This is a very long dictionary with nested items and I am guessing I have to use some kind of recursion

I am not sure how to go about this currently so I have no existing code to get from where I am which is a dictionary to a file.

The end result I am trying to get is the following including newlines and spacing:

<a>
    c = something else
    <d>
        e = some item
    </d>
</a>
<b>
    z = something else
    <s>
        f = some item
    </s>
</b>
user1601716
  • 1,893
  • 4
  • 24
  • 53

1 Answers1

7
d={'a':
    {'c':'something else',
     'd':{'e':'some item'}
    },
   'b':
    {'z':'something else',
     's':{'f':'some item'}
    }
}

def printer(d, t=0):
    for k, v in d.items():
        if isinstance(v, str):
            yield '\t' * t + '{} = {}'.format(k, v)
        else:
            yield '\t' * t + '<{}>'.format(k)
            yield from printer(v, t=t+1)
            yield '\t' * t + '</{}>'.format(k)

s = '\n'.join(printer(d))
print(s)

prints:

<a>
    c = something else
    <d>
        e = some item
    </d>
</a>
<b>
    z = something else
    <s>
        f = some item
    </s>
</b>
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91