Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ...?

like image 718
lurker Avatar asked Oct 30 '16 13:10

lurker


3 Answers

More compactly:

import re

s = 'SEQ(A=1%B=2)OPS(CC=0%G=2)T1(R=N)T2(R=Y)'
print dict(re.findall(r'(.+?)\((.*?)\)', s))
like image 186
hvwaldow Avatar answered Nov 05 '22 16:11

hvwaldow


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'}
like image 21
Bhargav Rao Avatar answered Nov 05 '22 16:11

Bhargav Rao


Alternatively, this could be solved with a regular expression:

>>> import re
>>> s = 'SEQ(A=1%B=2)OPS(CC=0%G=2)T1(R=N)T2(R=Y)'
>>> print dict(match.groups() for match in re.finditer('([^(]+)\(([^)]+)\)', s))
{'T1': 'R=N', 'T2': 'R=Y', 'SEQ': 'A=1%B=2', 'OPS': 'CC=0%G=2'}
like image 30
SimonC Avatar answered Nov 05 '22 16:11

SimonC