I'm struggling with a Python question and would appreciate any help. Do have patience, my Python is basic at the moment.
Question:
How do I transform a string structure like this:
text="key1=value1;key2=value2\nkeyA=valueA\n..."
into a Python dictionary like this:
{0:{'key1':'value1', 'key2':'value2'}, 1:{'keyA':'valueA'}}
There needs to be another function to transform this Python dictionary back into its original string form.
Where I am now:
I was thinking of creating a loop that is able to do this but I'm struggling to create it.
a[0]["key1"]="value1"
a[0]["key2"]="value2"
a[1]["keyA"]="valueA"
The best I did was to split the string by '\n' like this:
text ='k1=v1;k2=v2\nk3=v3\nk4=v4'
text = text.split("\n")
output: ['k1=v1;k2=v2', 'k3=v3', 'k4=v4']
And looped the elements into the dictionary like this:
dic = {}
for i,x in enumerate(text):
dic[i] = x
output: {0: 'k1=v1;k2=v2', 1: 'k3=v3', 2: 'k4=v4'}
But how do I get these values within the dictionary into the key, value structure as seen above?
You can use the following dict comprehension:
{i: dict(p.split('=', 1) for p in l.split(';')) for i, l in enumerate(text.split('\n')) if l}
With your sample input:
text="key1=value1;key2=value2\nkeyA=valueA\n"
This returns:
{0: {'key1': 'value1', 'key2': 'value2'}, 1: {'keyA': 'valueA'}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With