Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string with components separated by symbols into a nested python dictionary

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'}}
  1. Realize that ';' separates items in the inner dictionary while ‘\n’ separates items on the outer dictionary.
  2. The key, values in the inner dictionaries are strings. The keys for the outer dictionaries are indexes.

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?

like image 581
z-wei Avatar asked Jun 13 '26 20:06

z-wei


1 Answers

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'}}
like image 104
blhsing Avatar answered Jun 17 '26 03:06

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!