lurker lurker - 1 month ago 5
Python Question

Splitting bracket-separated string to a dictionary

I want to make this string to be dictionary.

s = 'SEQ(A=1%B=2)OPS(CC=0%G=2)T1(R=N)T2(R=Y)'


Following

{'SEQ':'A=1%B=2', 'OPS':'CC=0%G=2', 'T1':'R=N', 'T2':'R=Y'}


I tried this code

d = dict(item.split('(') for item in s.split(')'))


But an error occurred

ValueError: dictionary update sequence element #4 has length 1; 2 is required


I know why this error occurred, the solution is deleting bracket of end

s = 'SEQ(A=1%B=2)OPS(CC=0%G=2)T1(R=N)T2(R=Y'


But it is not good for me. Any other good solution to make this string to be dictionary type ...?

Answer

Add a if condition in your generator expression.

>>> s = 'SEQ(A=1%B=2)OPS(CC=0%G=2)T1(R=N)T2(R=Y)'
>>> s.split(')')
['SEQ(A=1%B=2', 'OPS(CC=0%G=2', 'T1(R=N', 'T2(R=Y', '']
>>> d = dict(item.split('(') for item in s.split(')') if item!='')
>>> d
{'T1': 'R=N', 'OPS': 'CC=0%G=2', 'T2': 'R=Y', 'SEQ': 'A=1%B=2'}
Comments